Kotlin memo
Published on 29 May 2022
Good links
Bit of various code
map reduce
Convert a list of bite to a list of string and summarize the list of string
in a string containing the concatenation. How to log the request sent(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
We can transform an entity into a domain model of DTO with 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]
Capture the 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 Forms Reference
apply
run, let, also, use, et `with`They offer different ways to treat objects. Each has its own use cases and behaviors. Furthermore, lambda reference forms enable making code 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 on which it is called.
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 block of code.
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 block of code.
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 on which it is called.
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 function`close`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 the lambda reference forms or the blocks`{}`, you can encapsulate the logic in separate functions, thereby improving the readability and reusability of the code.
let Function in Kotlin
The function`let`in Kotlin is used to perform operations on an object and return a different result. However, it is important to note that the function`let`does not modify the initial state of the object on which it is called
Signature |
|
Usage |
The function`let`is commonly used to apply transformations to an object and obtain a result based on those transformations. |
Result |
The value returned by the function`let`is the result of the lambda expression passed as an argument, usually the result of the operations performed on the object. |
Side Effects |
Although the function`let`may have side effects on the object when used in the lambda expression, it does not modify the initial state of the object itself. |
Thus, the function`let`is an elegant way to perform operations on an object while obtaining a derived result, while preserving the integrity of the original object.