how to implement an anonymous abstract class in Kotlin
TIL how to implement an anonymous abstract class in Kotlin. This is something you do all the time in Java with Android for example, when an interface calls for a single abstract method implementation. Consider the following Java code for example.
abstract class Foobar {
abstract String foo();
}
Foobar = new Foobar() {
@Override
String foo() {
return "foo!";
}
}
In Kotlin, the syntax proved a bit more tricky to track down - easily doable, just slightly elusive:
abstract class Foobar {
abstract fun foo(): String
}
class UsesFoo {
fun foo(foo:Foobar) {
println(foo)
}
}
fun main(args: Array<String>) {
UsesFoo().foo(object: Foobar() {
override fun foo(): String {
return "foo!"
}
})
}
Notice the "object:" portion of the above code?