Let's say I have an interface Base
and that we implement that interface in class Base1 : Base
.
I would expect an extension function in the form
fun ArrayList<Base>.myFun()
to also work on arrayListOf(Base1(), Base1()).myFun()
, but it doesn't. It requires the list to be of type Base
instead of Base1
.
Isn't this really strange? Or am I just missing something?
And, what are my options to write a function available on all subclasses of an interface?
Thanks!
In Kotlin we use a single colon character ( : ) instead of the Java extends keyword to extend a class or implement an interface. We can then create an object of type Programmer and call methods on it—either in its own class or the superclass (base class).
The . kt extension is the most common Kotlin file extension that's used to write Kotlin source code. This extension is used extensively when you're writing the code for your Android application.
In the Java section, let's assume we have the following Java file and we want to use our previously generated extension method in the same. You can use your Kotlin Extension method directly using this newly static file create by the Kotlin compiler.
You need to allow extension function to accept child implementation
interface Base
class Base1: Base
fun ArrayList<out Base>.myFun() = println(toString())
fun main(args: Array<String>) {
arrayListOf(Base1(), Base1()).myFun()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With