1. Kotlin / Говнокод #28891

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    @JvmInline
    value class Code(val value: Short) {
    
        companion object {
    
            fun from(value: Number): CurrencyCode {
                checkValid(value)
                return CurrencyCode(value.toShort())
            }
    
            private fun checkValid(value: Number) {
                val targetValue = value.toDouble()
                val isValueInvalid = floor(targetValue) != targetValue
                        || targetValue < 0
                        || targetValue > Short.MAX_VALUE
                if (isValueInvalid) {
                    throw DomainRuleViolationException(
                        "Code must be of 'short' type, greater than 0 and lower than ${Short.MAX_VALUE}. Provided: [$value]"
                    )
                }
            }
    
        }
    
        init {
            checkValid(value)
        }
    
    }

    Валидация данных приходящих в контроллер. При этом в проекте существует Эксепшнхендлер на неверный инпут от пользователя, который отлично работает еще во время десерелизации запроса.

    Boeing1337, 22 Декабря 2023

    Комментарии (0)
  2. Kotlin / Говнокод #27548

    −1

    1. 1
    val cityEq: (City) -> (Customer) -> Boolean = { city -> { it.city == city } }

    Какой Kotlin ^_^^_^^_^

    PolinaAksenova, 04 Августа 2021

    Комментарии (33)
  3. Kotlin / Говнокод #27436

    0

    1. 001
    2. 002
    3. 003
    4. 004
    5. 005
    6. 006
    7. 007
    8. 008
    9. 009
    10. 010
    11. 011
    12. 012
    13. 013
    14. 014
    15. 015
    16. 016
    17. 017
    18. 018
    19. 019
    20. 020
    21. 021
    22. 022
    23. 023
    24. 024
    25. 025
    26. 026
    27. 027
    28. 028
    29. 029
    30. 030
    31. 031
    32. 032
    33. 033
    34. 034
    35. 035
    36. 036
    37. 037
    38. 038
    39. 039
    40. 040
    41. 041
    42. 042
    43. 043
    44. 044
    45. 045
    46. 046
    47. 047
    48. 048
    49. 049
    50. 050
    51. 051
    52. 052
    53. 053
    54. 054
    55. 055
    56. 056
    57. 057
    58. 058
    59. 059
    60. 060
    61. 061
    62. 062
    63. 063
    64. 064
    65. 065
    66. 066
    67. 067
    68. 068
    69. 069
    70. 070
    71. 071
    72. 072
    73. 073
    74. 074
    75. 075
    76. 076
    77. 077
    78. 078
    79. 079
    80. 080
    81. 081
    82. 082
    83. 083
    84. 084
    85. 085
    86. 086
    87. 087
    88. 088
    89. 089
    90. 090
    91. 091
    92. 092
    93. 093
    94. 094
    95. 095
    96. 096
    97. 097
    98. 098
    99. 099
    100. 100
    package com.example
    
    import kotlinx.coroutines.*
    import io.ktor.network.selector.*
    import io.ktor.network.sockets.*
    import io.ktor.utils.io.*
    import kotlinx.coroutines.channels.BroadcastChannel
    import kotlinx.coroutines.channels.ClosedReceiveChannelException
    import kotlinx.coroutines.channels.ConflatedBroadcastChannel
    import kotlinx.coroutines.channels.ReceiveChannel
    import java.io.IOException
    import java.lang.StringBuilder
    import java.nio.ByteBuffer
    
    suspend fun ByteReadChannel.readString(): String {
        val result = StringBuilder()
        val decoder = Charsets.US_ASCII.newDecoder()
        val buffer = ByteBuffer.allocate(1)
        while (!isClosedForRead) {
            val byte = readByte()
            if (byte > 127 || byte < 0) {
                continue
            }
            val c = decoder.decode(buffer.also {
                it.put(byte)
                it.rewind()
            })[0]
            result.append(c)
            if (c == '\n') {
                return result.toString().trim('\r', '\n')
            }
            buffer.rewind()
            decoder.reset()
        }
        return ""
    }
    
    suspend fun ByteWriteChannel.println(text: String) {
        writeStringUtf8(text)
        writeStringUtf8("\r\n")
    }
    
    class Client(private val clientSocket: Socket, private val room: BroadcastChannel<String>) {
        private val output = clientSocket.openWriteChannel(autoFlush = true)
        private val input = clientSocket.openReadChannel()
        var nick: String? = null
            private set
    
        suspend fun start() = coroutineScope {
            input.discard(input.availableForRead.toLong())
    
            output.writeStringUtf8("Welcome! And your name: ")
            val nick = input.readString()
            room.send("$nick is here")
            output.println("Welcome $nick")
            [email protected] = nick
            val roomSubscription = room.openSubscription()
            launch {
                for (message in roomSubscription) {
                    output.println(message)
                }
            }
            launch {
                processUserInput(nick)
            }.join()
            roomSubscription.cancel()
        }
    
        private suspend fun processUserInput(nick: String) {
            while (!clientSocket.isClosed) {
                val text = input.readString()
                room.send("$nick: $text")
                if (text == "bye") {
                    room.send("$nick left")
                    return
                }
            }
        }
    }
    
    
    suspend fun stdoutRoomProcessor(input: ReceiveChannel<String>) {
        for (message in input) {
            println(message)
        }
    }
    
    suspend fun server(port: Int) = coroutineScope {
        val serverSocket = aSocket(ActorSelectorManager(coroutineContext)).tcp().bind(port = port)
        val room = ConflatedBroadcastChannel<String>()
        launch {
            stdoutRoomProcessor(room.openSubscription())
        }
        while (coroutineContext.isActive) {
            val clientSocket = serverSocket.accept()
            room.send("Client connected ${clientSocket.remoteAddress}")
            launch {
                val client = Client(clientSocket, room)
                try {
                    client.start()

    MAKAKA, 22 Мая 2021

    Комментарии (44)
  4. Kotlin / Говнокод #27176

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    * Returns the largest value among all values produced by [selector] function
     * applied to each element in the collection.
     * 
     * @throws NoSuchElementException if the collection is empty.
     */
    @SinceKotlin("1.4")
    @OptIn(kotlin.experimental.ExperimentalTypeInference::class)
    @OverloadResolutionByLambdaReturnType
    @kotlin.internal.InlineOnly
    public inline fun <T, R : Comparable<R>> Iterable<T>.maxOf(selector: (T) -> R): R {
        val iterator = iterator()

    MAKAKA, 25 Декабря 2020

    Комментарии (48)
  5. Kotlin / Говнокод #27165

    +1

    1. 1
    2. 2
    val users = listOf("foo", "bar")
    println(users.joinToString{","})

    MAKAKA, 15 Декабря 2020

    Комментарии (20)
  6. Kotlin / Говнокод #27133

    +2

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    9. 9
    private fun findFirstChecked(calendarModel: CalendarModel) =
            LocalDate.parse(
                "${calendarModel.year}-${
                    calendarModel.months.indexOfFirst {
                        it.state is
                                CalendarMonthState.EnableType
                    }.plus(1).toString().padStart(2, '0')
                }-01"
            )

    Та хрен его знает что оно делает. Вроде бы находит выбранный месяц календаря, но это не точно.

    DarkPerenL, 25 Ноября 2020

    Комментарии (6)
  7. Kotlin / Говнокод #27087

    +1

    1. 1
    2. 2
    Currently it's hard or even impossible to use hexadecimal literal constants that result in overflow of the corresponding signed types. 
    https://github.com/Kotlin/KEEP/blob/master/proposals/unsigned-types.md

    какой пиздец!!!

    MAKAKA, 06 Ноября 2020

    Комментарии (105)
  8. Kotlin / Говнокод #27030

    +2

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    9. 9
    object Cорок {
        infix fun тысяч(b: String) = this
        infix fun в(a: String) = this
        infix fun сунули(a: String) = this
    }
    
    fun main() {
        Cорок тысяч "обезъян" в "жопу" сунули "банан"
    }

    DypHuu_niBEHb, 15 Октября 2020

    Комментарии (57)
  9. Kotlin / Говнокод #26591

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    enum class Measures {
        B, KB, MB, GB;
    
        private val size = BigDecimal.valueOf(1024L).pow(ordinal)
    
        companion object {
            fun toHumanSize(value: Long): String {
                val decValue = value.toBigDecimal()
                val measure = values().reversed().find { it.size < decValue } ?: B
                return "${decValue.divide(measure.size, 3, RoundingMode.UP)} $measure"
    
            }
        }
    }

    MAKAKA, 20 Апреля 2020

    Комментарии (142)
  10. Kotlin / Говнокод #26408

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    data class User(
    
        @Expose
        @SerializedName("email")
        val email: String? = null,
    
        @Expose
        @SerializedName("username")
        val username: String? = null,
    
        @Expose
        @SerializedName("image")
        val image: String? = null
    ) {
        override fun toString(): String {
            return "User(email=$email, username=$username, image=$image)"
        }
    }

    JetBrains сделали прекрасный стандартный toString у дата классов, а они всё равно пишут свой туСтринг, который выдаёт результат в точности повторяющий стандартный.

    https://github.com/mitchtabian/MVIExample/blob/master/app/src/main/java/com/codingwithmitch/mviexample/model/User.kt

    Gorr, 03 Февраля 2020

    Комментарии (76)