
Those currently have some issues during the code generation phase at this point, so for now they are prohibited. 💡 Extra bulletsĪn interface with a single suspend function cannot be used as a SAM. There are interesting gotchas regarding this like the one described on this post by Vasya Drobushkov, so it’s good to keep this in mind. When Kotlin lambdas are not capturing (they only access final variables), they can be instantiated as a singleton object per application, so same instance can be reused every time without an additional cost on memory allocation.įor interfaces in the other hand that’s different, since Kotlin creates a new object for each call. More details on that on this post by Tompee Balauag. When that happens, Kotlin wraps those in Ref and captures them for their usage within the lambda. Lambdas in Kotlin can reference external non-final variables, not like in Java. Here you have the community discussion that triggered the feature development later on. They just realized now there are some scenarios where it could be convenient. That is precisely the same doubt the Kotlin team had for not introducing those before. Kotlin has support for function types and function literals (lambdas), so that is a reasonable doubt to have. 🤔 Why would I use it for Kotlin interfaces? Some of those are Comparator, ReadOnlyProperty and PropertyDelegateProvider.

Some interfaces widely used from the Kotlin stdlib are also flagged as fun interface now.

They are possible when the input and output types for the Java SAM and the Kotlin function match. The ultimate idea is that you can call a Java SAM as if you were calling a simple function. The main goal for this feature is interoperability.

Kotlin can sugarize any Java interfaces that follow that pattern into lambdas to leverage interoperability. That is actually the name they have in Java. These interfaces are also called “functional interfaces” frequently because their only purpose is to be used as a function. Those that are frequently used as callbacks. SAM stands for Single Abstract Method and it refers to interfaces with a single non-default method. This feature also exists in other JVM languages like Java 8 or Scala. About Kotlin SAM support for Java interoperability and also for Kotlin interfaces starting on release 1.4.
