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.
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.
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