Why Kotlin Lambda functional interfaces are not implementing Serializable?

For instance:

lateinit var l0 : () -> (Int)
lateinit var l1 : (Int) -> (Int)
lateinit var l2 : (Int, Int) -> (Int)

Function0, Function1, Function2 do not implement Serializable.

The only way to do this would be to use a custom defined functional interface:

@FunctionalInterface
public interface SerializableConsumer<T> extends Serializable
{
    void consume(T arg);
}

And then:

doSomething(SerializableConsumer { arg ->
    println(arg)
})

This would be useful in Android development, since you could pass this lambda to a Fragment or Activity, using an Intent or Bundle.

The Serializable could be thought of as a marker interface for the author to opt-in their thing as serializable. If all lambda’s were serializable by default, how would you say that your lambda isn’t serializable?

Assuming all lambda’s should be considered serializable (or serializable by default) is a broad assumption

EDIT: There’s some really interesting discussion on an old Java mailing list on why Java decided to go with defaulting to non-serializable and using a marker interface. I’ll link it here if I find it again.

1 Like

Your reasoning is fair enough.

I do understand though, that simple constant lambda literals feel like primitive values that should be serializable by nature:

var f = { i: Int -> i + 1 }

1 Like