gpt4 book ai didi

android - 界面上的 Kotlin 扩展

转载 作者:IT老高 更新时间:2023-10-28 13:37:51 30 4
gpt4 key购买 nike

假设我有一个 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com