Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize a lambda in kotlin

Tags:

lambda

kotlin

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:

enter image description here

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 ?

like image 946
j2emanue Avatar asked Oct 05 '18 03:10

j2emanue


People also ask

What is Lambdas 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,

What is data serialization in Kotlin?

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.

What is a function in Kotlin?

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.

What is type inference in Kotlin Lambda?

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:


1 Answers

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")
    }
}
like image 117
Rene Avatar answered Oct 13 '22 20:10

Rene