https://kotlinlang.org logo
Title
b

bodiam

03/06/2020, 7:05 AM
What is the Java equivalent of this code:
interface MyInterface<out T> {
    fun process(): T
}
I need to convert this interface to Java because of SAM conversion, but I'm failing a bit here.
e

Eivind Nilsbakken

03/06/2020, 7:30 AM
interface MyInterface<T> {
    T process();
}
b

bodiam

03/06/2020, 7:31 AM
Thanks, but are you super? I don't think that's matching the
out
parameter in my interface.
b

bezrukov

03/06/2020, 7:31 AM
I think there is no equivalent code in java (in java there is no idiomatic and safe way to use Interface<T> as Interface<ParentT> - you need to perform explicit cast) SAM conversion for kotlin interfaces will be supported in 1.4. Before it released you can write top-level fun
fun MyInterface(lambda): MyInterface = ...
e

Eivind Nilsbakken

03/06/2020, 7:32 AM
Oh, yeah. ☝️
b

bodiam

03/06/2020, 7:32 AM
Thanks Denis, but what do you mean with the last line?
Right now I have:
return object: MyInterface<Any> {
   override fun process(): String = {
      // code here
   }
}
but I'd like to make it a bit shorter.
b

bezrukov

03/06/2020, 7:35 AM
inline fun <reified T> MyInterface(crossinline lambda: () -> T) = object : MyInterface<T> {
    override fun process(): T {
        return lambda()
    }
}
then just use it
val interface: MyInterface<String> = MyInterface { "Looks like it's SAM conversion" }
val anyInterface: MyInterface<Any> = interface
so you will write:
return MyInterface {
    // code here
}
r

Ruckus

03/06/2020, 2:43 PM
Maybe a dumb question, but is there a reason you're not just using
() -> T
?
b

bodiam

03/08/2020, 6:14 AM
I'm not sure what you mean with
() -> T
?
@bezrukov It worked really well btw, thanks for that!!