作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
假设我有一个 interface Base
并且我们在 class Base1 : Base
中实现该接口(interface)。
我希望表单中有一个扩展函数
fun ArrayList<Base>.myFun()
也适用于 arrayListOf(Base1(), Base1()).myFun()
,但它没有。它要求列表的类型为 Base
而不是 Base1
。
这真的很奇怪吗?还是我只是错过了什么?
而且,我有哪些选项可以编写一个可用于接口(interface)的所有子类的函数?
谢谢!
最佳答案
你需要允许扩展函数接受子实现
interface Base
class Base1: Base
fun ArrayList<out Base>.myFun() = println(toString())
fun main(args: Array<String>) {
arrayListOf(Base1(), Base1()).myFun()
}
关于android - 界面上的 Kotlin 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50757005/
我是一名优秀的程序员,十分优秀!