Kotlin SAM traits as lambda functions


around M5-M6 Kotlin gained support for calling java SAM's (Single Abstract Methods, think Runnable Interface) with a lambda function.  This allowed you to do

//kotlin code SwingUtilities.invokeLater{   //some code here }

//is the same as this code
SwingUtilities.invokeLater(object : Runnable {
  override fun run() {
  //some code here

However if the SAM is a kotlin Trait, this does not work for some reason... are their plans to allow Kotlin SAM Traits to be called like Lambda's

Thank you - Matt

Why Diffrence of annomous Impl of Interface declared in between Java and Kotlin

There are no such plans, because Kotlin has proper function types which render SAM-conversions unnecessary for Kotlin



Thank you for the quick response.  I believe the conversion would be useful because it allows me to design with meaningful Interfaces.  When implementing the Interfaces if it is simple use a lambda, and if it is more substantial use a class.

Thank you again - Matt


I think your use case will be solved once we support type aliases, since Kotlin function types are actually normal traits


I made a similar request not long ago:



To clarify does this mean the workaround for this issue is that when you want a 'SAM interface' you write this a a java interface rather than a Kotlin trait?

Thanks, Rob.


It's enough to use function type, no need to resort to Java.


Could you elaborate on that, Andrey? Traits don't have state, right? I think what was meant is - with a Java event listener, for example, you could assign a lambda to it if the handler is simple, and if the handler needs some associated state maintained across invocations you'd just use a traditional anonymous class. In Kotlin it has to be a function no matter what, so then you'd need (I guess) a separate object definition and to set the handler using "myHandler::onFoo" type syntax?


A lambda can have "associated state": its closure works very well for that



What about Java interop with a library written in Kotlin? If I write a library that should be useable from Java code as well, and would like to define a Java interface type as parameter for the method, I can no longer call it inside Kotlin with a lambda. Is this correct? It sounds like SAM for methods defined in Kotlin would be sensible here as well?

Or has the matter changed since the original discussion?