Kotlin: Interface ... does not have constructors
The best solution is to use a typealias in-place of your Java interface
typealias MyInterface = (Location) -> Unit
fun addLocationHandler(myInterface:MyInterface) {
}
Register it like this:
val myObject = { location -> ...}
addLocationHandler(myObject)
or even cleaner
addLocationHandler { location -> ...}
Invoke it like this:
myInterface.invoke(location)
The 3 current options seem to be:
- typealias (messy when called from java)
- kotlin interface (messy when called from kotlin; you need to create an object) This is a big step back IMO.
- java interface (less messy when called from kotlin; lambda needs interface name prepended so you don't need an object; also can't use lambda outside of function parenthesis convention)
When converting our libraries to Kotlin, we actually left all the interfaces in Java code, as it was cleaner to call Java from Kotlin than Kotlin from Kotlin.
Try to access to your interface like this :
object : MyInterface {
override fun onSomething() { ... }
}
Your Java code relies on SAM conversion - an automatic conversion of a lambda into an interface with a single abstract method. SAM conversion is currently not supported for interfaces defined in Kotlin. Instead, you need to define an anonymous object implementing the interface:
val obj = object : MyInterface {
override fun onLocationMeasured(location: Location) { ... }
}
SAM conversion is supported for interfaces defined in Kotlin since 1.4.0
What's New in Kotlin 1.4.0
Before Kotlin
1.4.0
, you could apply SAM (Single Abstract Method) conversions only when working with Java methods and Java interfaces from Kotlin. From now on, you can use SAM conversions for Kotlin interfaces as well. To do so, mark a Kotlin interface explicitly as functional with thefun
modifier.
SAM conversion applies if you pass a lambda as an argument when an interface with only one single abstract method is expected as a parameter. In this case, the compiler automatically converts the lambda to an instance of the class that implements the abstract member function.
So the example in Your question will look something like this:
fun interface MyInterface
{
fun onLocationMeasured(location: String)
}
fun main()
{
val myObj = MyInterface { println(it) }
myObj.onLocationMeasured("New York")
}