I am trying to serialize a lambda as in java 8 which is performed like this:
Runnable r = (Runnable & Serializable)() ->{doSomething();};
but when it try the same thing in kotlin like this:
val r = { doSomething() } as (Runnable , Serializable)
i get a compile error of:
even if i try to paste the java code into kotlin file it will remove the serializable portion of the cast. therefore how to serialize lambda in kotlin ?
Kotlin Lambdas. Lambda Expressions. Lambda expression or simply lambda is an anonymous function; a function without name. These functions are passed immediately as an expression without declaration. For example,
In Kotlin, data serialization tools are available in a separate component, kotlinx.serialization. It consists of two main parts: the Gradle plugin – org.jetbrains.kotlin.plugin.serialization and the runtime libraries.
To facilitate this, Kotlin, as a statically typed programming language, uses a family of function types to represent functions, and provides a set of specialized language constructs, such as lambda expressions. A higher-order function is a function that takes functions as parameters, or returns a function.
The type of the last command within a lambda block is the returned type. 2.1. Type Inference Kotlin’s type inference allows the type of a lambda to be evaluated by the compiler. Writing a lambda that produces the square of a number would be as written as:
Kotlin lambdas are serializable by default, see https://discuss.kotlinlang.org/t/are-closures-serializable/1620.
So this will work:
val r = { println("Hallo")} as java.io.Serializable
If you really need a Runnable then this does not work, because Kotlin creates only a Runnable instance:
val r = Runnable { println("Hallo")} as java.io.Serializable
In this case you have to explicitly create an object:
val r = object: Runnable, java.io.Serializable {
override fun run() : Unit {
println("Hallo")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With