What would be the equivalent of that code in kotlin, nothing seems to work of what I try:
public interface AnInterface {
void doSmth(MyClass inst, int num);
}
init:
AnInterface impl = (inst, num) -> {
//...
}
What would be the equivalent of that code in kotlin, nothing seems to work of what I try:
public interface AnInterface {
void doSmth(MyClass inst, int num);
}
init:
AnInterface impl = (inst, num) -> {
//...
}
If AnInterface is Java, it can work with SAM conversion:
val impl = AnInterface { inst, num ->
//...
}
Otherwise, if the interface is Kotlin:
Since Kotlin 1.4, it's possible to write functional interfaces :
fun interface AnInterface {
fun doSmth(inst: MyClass, num: Int)
}
val impl = AnInterface { inst, num -> ... }
Otherwise, if the interface is not functional
interface AnInterface {
fun doSmth(inst: MyClass, num: Int)
}
you can use the object syntax for implementing it anonymously:
val impl = object : AnInterface {
override fun doSmth(inst:, num: Int) {
//...
}
}
If you're rewriting both the interface and its implementations to Kotlin, then you should just delete the interface and use a functional type:
val impl: (MyClass, Int) -> Unit = { inst, num -> ... }
val listener: (name: Class, other: OtherClass) -> Unit(String) -> String Without a name, you can't reason about it. Now, what does a function with this signature do? (UserId) -> PhoneNumber - Well, the only reasonable implementation would be something that looks up user data by ID, then pulls out the phone number and returns it. If your functions don't take primitives then you don't usually need to wrap them in an interface for readability.You can use an object expression
So it would look something like this:
val impl = object : AnInterface {
override fun(doSmth: Any, num: Int) {
TODO()
}
}
To anyone who is reading this in 2022, Kotlin now has Functional (SAM) Interfaces. Please see https://kotlinlang.org/docs/fun-interfaces.html
Maybe it will save others some time depending on your use case.