Kotlin Memo
Published on 29 May 2022
Good links
Miscellaneous code snippets
map reduce
Convert a list of bytes to a list of strings and summarize the list of strings
into a string containing the concatenation. How to log the sent request(requestBodyContent:byte[])
log.info(
requestBodyContent!!.map { it.toInt().toChar().toString() }
.reduce { request: String, s: String -> request + s }
)
enum and sealed classes
functional interface and method reference
An entity can be transformed into a domain model or dto using a method reference(functional style- java 8)
fun findAllByLoginNot(
pageable:Pageable,
login:String)
:Page<UserDto> {
return userDao.findAllByLoginNot(
pageable,
login).map(::fromEntity)
}
ahttps://stackoverflow.com/a/22245383/837404[good explanation]
Capturing standard output
package functional
import java.io.ByteArrayOutputStream
import java.io.PrintStream
import java.lang.System.out
import java.lang.System.setOut
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
class BasicsHOF {
private val standardOut: PrintStream? = out
private val outputStreamCaptor = ByteArrayOutputStream()
@BeforeTest
fun setUp() = setOut(PrintStream(outputStreamCaptor))
@AfterTest
fun tearDown() = setOut(standardOut)
@Test
fun `three times dope`() {
3.times { println("Hello") }
assertEquals(
buildString {
repeat(3) { append("Hello\n") }
deleteAt(length - 1)
}, outputStreamCaptor
.toString()
.trim()
)
}
fun Int.times(fn: () -> Unit) = (1..this).forEach { _ -> fn() }
}
What is the difference in kotlin between apply, run, let, also, use and with ?
Comparison of Kotlin functions and Use of Lambda Reference Forms
apply
run, let, also, use, et `with`offer different ways to handle objects. Each has its own use cases and behaviors. Furthermore, lambda reference forms allow the code to be more readable and reusable by referencing existing lambda functions.The function`apply`is used to configure an object during its creation. It returns the object it was called on.
Example with lambda reference:
val someObject = SomeClass().apply(::configureObject)
Example with lambda:
val someObject = SomeClass().apply {
// configuration des propriétés de someObject
}
run
The function`run`is used to execute a block of code on an object and returns the result of the code block.
Example with lambda reference:
val result = someObject.run(::someFunction)
Example with lambda:
val result = someObject.run {
// bloc de code à exécuter sur someObject
// la dernière expression est renvoyée
}
let
The function`let`is used to execute a block of code on an object and returns the result of the code block.
Example with lambda reference:
val result = someObject.let(::processObject)
Example with lambda:
val result = someObject.let {
// bloc de code à exécuter sur someObject
// la dernière expression est renvoyée
}
also
The function`also`is used to perform an additional action on an object and returns the object it was called on.
Example with lambda reference:
someObject.also(::performAdditionalAction)
Example with lambda:
someObject.also {
// action additionnelle sur someObject
}
use
The function`use`is used to work with resources that must be closed after use. It automatically calls the`close`function at the end of the block.
Example with lambda reference:
someResource.use(::useResource)
Example with lambda:
someResource.use {
// travailler avec la ressource
}
with
The function`with`is used to call multiple methods on an object without repeating its name and returns the result of the last expression.
Example with lambda reference:
val result = with(someObject, ::processWithObject)
Example with lambda:
val result = with(someObject) {
// appeler des méthodes sur someObject
// la dernière expression est renvoyée
}
By using lambda reference forms or`{}`blocks, you can encapsulate logic into separate functions, thereby improving code readability and reusability.
let Function in Kotlin
The`let`function in Kotlin is used to perform operations on an object and return a different result. However, it is important to note that the`let`function does not modify the initial state of the object it is called on.
Signature |
|
Usage |
The`let`function is commonly used to apply transformations to an object and obtain a result based on those transformations. |
Result |
The value returned by the`let`function is the result of the lambda expression passed as an argument, generally the result of the operations performed on the object. |
Side Effects |
Although the`let`function may have side effects on the object when used within the lambda expression, it does not modify the initial state of the object itself. |
Thus, the`let`function is an elegant way to perform operations on an object while obtaining a derived result, while preserving the integrity of the original object.