Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin extension on interface

Tags:

android

kotlin

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!

like image 677
Algar Avatar asked Jun 08 '18 09:06

Algar


People also ask

How do I extend an interface in Kotlin?

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).

What is the extension for Kotlin files?

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.

Can I use Kotlin extension function in Java?

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.


1 Answers

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()

}
like image 81
ruX Avatar answered Nov 01 '22 04:11

ruX