Are closures serializable?

I’m porting my Vaadin app to Kotlin, converting Vaadin listeners into closures. All Vaadin listeners are Serializable; I’m therefore wondering whether the Kotlin closures are serializable or not. I have found no doc on this; I tried running this code and it seems working properly:

fun Any.serializeToBytes(): ByteArray = ByteArrayOutputStream().use { it -> ObjectOutputStream(it).writeObject(this); it }.toByteArray()
inline fun <reified T: Any> ByteArray.deserialize(): T = ObjectInputStream(inputStream()).readObject() as T
inline fun <reified T: Any> T.serializeDeserialize() = serializeToBytes().deserialize<T>()
{ println("foo") }.serializeDeserialize()()

prints “foo” correctly. However, when calling Kotlin code from Java, the Functionx interfaces are not themselves marked serializable.
Thank you :wink:

Yes, function types do not inherit from java.io.Serializable, however each lambda on JVM internally is serializable, so it’s safe to cast lambdas or function expressions to java.io.Serializable. Feel free to vote/watch this issue: https://youtrack.jetbrains.com/issue/KT-10671

2 Likes

Thank you for letting me know. I think KT-11254 is more close to this issue, I have added a link to this forum there.

Actually, in Kotlin 2.0.0, the Kotlin closures are no longer serializable by default: What's new in Kotlin 2.0.0 | Kotlin Documentation . One of the solutions is to annotate the lambda with @JvmSerializableLambda.