【问题标题】:Can kotlin interface detects, on which class is attached to, on its own?kotlin 接口可以自行检测附加到哪个类吗?
【发布时间】:2023-02-02 00:51:49
【问题描述】:

我有通用接口...

interface Parent<T> {
    fun function(entity: T): Int
}

当我用一些子类实现功能时......

class Other : Parent<Other> {
    override fun function(entity: Other): Int {
        return 42
    }
}

我对在实现接口时必须传递相同的类类型这一事实感到困扰......我真的希望接口能够检测到它自己附加了哪个类,而无需我再次提供相同的类型...

我想要这样的代码......

class Other : Parent {
    override fun function(entity: Other): Int {
        return 42
    }
}

在科特林中是否有可能以某种形式做到这一点?

【问题讨论】:

  • 这不可能。

标签: kotlin generics


【解决方案1】:

不是在一般情况下,但有时当泛型完全受另一个约束时:https://kotlinlang.org/docs/generics.html#underscore-operator-for-type-arguments

【讨论】:

    猜你喜欢
    • 2021-03-05
    • 2018-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-10
    • 2013-08-14
    • 2012-12-14
    • 2021-02-16
    相关资源
    最近更新 更多