How to create an instance of an anonymous interface in Kotlin?
Hello everyone! I just started learning Kotlin after Java and encountered a problem. In Java, I often used anonymous classes for interfaces, for example, for click handlers or listeners. Here's how I did it in Java:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("Clicked!");
}
});
Now I'm trying to do the same in Kotlin, but I can't get it to work. I have a simple interface:
interface ClickListener {
fun onClick()
}
I want to create an instance of this interface directly in the code, without creating a separate class. In Java it was simple: `new ClickListener() { ... }`. But in Kotlin I'm trying different options and none of them work:
No answers yet.
Log in to leave an answer
Blogs
Docker and Java: Application Containerization for Developers
@Override Error in Eclipse: How to Defeat "Must Override a Superclass Method"
Indices in forEach Kotlin: How Not to Lose Position and Speed Up Code
Converting a String to a Boolean Value in JavaScript: A Complete Guide