07-20-2023, 04:07 PM
I am working on an android library that contains some views. Naturally these views can emit events.
I have an interface called (just for the purpose of this question) `Listener`. If I wrote the library in Java things would look like this:
```java
public interface Listener {
void onEvent();
}
```
```java
public class SomeView extends FrameLayout {
// Some more functions and implementation details
public void setListener(Listener l) { ... }
}
```
When using this view in a Kotlin activity I can use the `setListener` like this:
```Kotlin
someViewInstance.setListener {
// implementation
}
```
I want to write my library in Kotlin, but it might be used in Java code as well, so I want to provide and interface for the listener just like a regular view (like above) but have the option for Kotlin code to use the function implementation:
```Kotlin
interface Listener {
fun onEvent()
}
```
when I try to use `setListener` like above in my Kotlin test activity I get a compilation error saying that the function expects type `Listener` but got `() -> Unit`.
Is there a way to enable this kind of implementation in Kotlin without having to create a new function for this?
I thought about having just one function that receives `() -> Unit` but then it look weird in the Java code (`Function1` etc.).
Thanks!
I have an interface called (just for the purpose of this question) `Listener`. If I wrote the library in Java things would look like this:
```java
public interface Listener {
void onEvent();
}
```
```java
public class SomeView extends FrameLayout {
// Some more functions and implementation details
public void setListener(Listener l) { ... }
}
```
When using this view in a Kotlin activity I can use the `setListener` like this:
```Kotlin
someViewInstance.setListener {
// implementation
}
```
I want to write my library in Kotlin, but it might be used in Java code as well, so I want to provide and interface for the listener just like a regular view (like above) but have the option for Kotlin code to use the function implementation:
```Kotlin
interface Listener {
fun onEvent()
}
```
when I try to use `setListener` like above in my Kotlin test activity I get a compilation error saying that the function expects type `Listener` but got `() -> Unit`.
Is there a way to enable this kind of implementation in Kotlin without having to create a new function for this?
I thought about having just one function that receives `() -> Unit` but then it look weird in the Java code (`Function1` etc.).
Thanks!