Let's say I have an interface Base and that we implement that interface in class Base1 : Base.

我希望表单中有一个扩展函数

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.

这不是很奇怪吗?或者我只是错过了什么?

And, what are my options to write a function available on all subclasses of an interface?

谢谢!

推荐答案

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

}

Kotlin相关问答推荐

KTOR';S函数`staticResources`在Kotlin本机目标上不可用

Criteria Api 中的 Kotlin 泛型

kotlin 模式匹配如何像 scala 一样工作

为什么 <= 可以应用于 Int 和 Long,而 == 不能?

MyType.()在 Kotlin 中是什么意思?

JetPack Compose:添加点击持续时间

我可以在 Kotlin 中使用接口类型作为构造函数参数吗

如何判断给定字符串是否多次包含另一个子字符串?

从 Kotlin 调用 Java 时可以为空的规则是什么

添加 Kapt 插件后 - 执行 org.jetbrains.kotlin.gradle.internal.KaptExecution 时发生故障

错误:cannot find symbol import com.gourav.news.databinding.ActivityDetailBindingImpl;

OnClickListener 未在 ConstraintLayout 上触发

Kotlin 插件错误:无法为类 org.jetbrains.kotlin.gradle.tasks.KotlinCompile 生成代理类

如何使用 gradle 脚本 Kotlin 构建文件构建可运行的 ShadowJar?

类型不匹配推断类型为单位,但应为空

uses-sdk:minSdkVersion 16 不能小于库中声明的版本 23

在android java类中使用Kotlin扩展

Android Studio - java.io.IOException:无法生成 v1 签名

我应该在哪里调用 MobileAds.initialize()?

如何在 Intellij Idea 中运行 Kotlin 函数