How can I convert () -> Unit
to a String and back to an executable method? From what I've seen so far lambdas in Kotlin are Serializables, which should be half way to the solution, but I cannot figure out how to make this conversion.
Asked
Active
Viewed 609 times
3

Willi Mentzel
- 27,862
- 20
- 113
- 121

AsafK
- 2,425
- 3
- 32
- 38
1 Answers
3
If the only constraint is that the result be a String
, then you can actually serialize the instance of the function type to a byte array and convert it to a String
in any way that will let you do the reverse, such as encode it with Base64.
Here's how you encode it:
val f: (Int) -> Int = { it * 2 }
val serialized = ByteArrayOutputStream().run {
ObjectOutputStream(this).apply { writeObject(f) }
toByteArray()
}
val string = Base64.getEncoder().encodeToString(serialized)
And here's how to decode it back:
val decoded = Base64.getDecoder().decode(string)
@Suppress("UNCHECKED_CAST")
val deserialized: (Int) -> Int =
ObjectInputStream(ByteArrayInputStream(decoded))
.readObject() as (Int) -> Int
Here's a complete runnable example: (link)
Note that for this to work, the side that decodes the string to a function instance must have the same class loaded for the lambda as the side that encoded it, as otherwise deserializing it will likely fail.

hotkey
- 140,743
- 39
- 371
- 326