Pass interface as parameter in Kotlin
Attached is an example of how to pass an object by parameter that represents the value of the data type and invoke behaviors using interface inheritance.
fun main() { val customClass = CustomClass( object : First { override fun first() { super.first() println("first new impl") } override fun second() { super.second() println("second new impl") } } ) customClass.first.first() customClass.first.second()}data class CustomClass(val first: First)interface First: Second { fun first() { println("first default impl") }}interface Second { fun second() { println("second default impl") }}
It is worth mentioning that with super.first()
or super.second()
the default behavior of the interface is being invoked.
It doesn't make much sense to pass a lamda with an anonymous object as a parameter, lambda: () -> Unit
, if what we need is to invoke the functions.
GL