- 1
val cityEq: (City) -> (Customer) -> Boolean = { city -> { it.city == city } }
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
−1
val cityEq: (City) -> (Customer) -> Boolean = { city -> { it.city == city } }
Какой Kotlin ^_^^_^^_^
0
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()
0
* 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()
+1
val users = listOf("foo", "bar")
println(users.joinToString{","})
+2
private fun findFirstChecked(calendarModel: CalendarModel) =
LocalDate.parse(
"${calendarModel.year}-${
calendarModel.months.indexOfFirst {
it.state is
CalendarMonthState.EnableType
}.plus(1).toString().padStart(2, '0')
}-01"
)
Та хрен его знает что оно делает. Вроде бы находит выбранный месяц календаря, но это не точно.
+1
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
какой пиздец!!!
+2
object Cорок {
infix fun тысяч(b: String) = this
infix fun в(a: String) = this
infix fun сунули(a: String) = this
}
fun main() {
Cорок тысяч "обезъян" в "жопу" сунули "банан"
}
0
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"
}
}
}
0
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
0
// One workaround is to approximate a namespace by using with a singleton object class.
object FooActions {
fun foo() {...}
}
Им дали возможность описывать функции на уровне пакета, без надобности совать их в MyOhuennyeUtils, а они жалуются что нету неймспейсов и пихают функци в класы. Долбоебы ¯\_(ツ)_/¯
https://medium.com/keepsafe-engineering/kotlin-the-good-the-bad-and-the-ugly-bf5f09b87e6f#3a98