【问题标题】:Why this code is not possible in Kotlin?为什么这个代码在 Kotlin 中是不可能的?
【发布时间】:2018-05-14 11:03:02
【问题描述】:

下面是 C++、C# 和其他类似语言的完美构造。为什么这在 Kotlin 中是不可能的

open class EndPoint<T> (url: String): T{

...
}

class BlueEndPoint: EndPoint<BlueInterface>{}
class RedEndPoint: EndPoint<RedInterface>{}

【问题讨论】:

    标签: design-patterns kotlin


    【解决方案1】:

    因为 Kotlin 使用泛型,而不是模板。它只有一个 EndPoint 类,而不是像 C++ 那样为每个 T 创建一个新类。

    在 JVM 上,这个类需要恰好扩展一个超类(可能是 Object)和一组特定的接口(可能没有)。 IE。你不能让 EndPoint&lt;BlueInterface&gt; 实现 BlueInterface 而不是 RedInterface,反之亦然 EndPoint&lt;RedInterface&gt;

    根据 MSDN,它在 C# 中也不起作用(我相信 CLR 在定义类时也有相同的要求):

    C# does not allow the type parameter to be used as the base class for the generic type.

    这里的例外是 C++。

    【讨论】:

    • 我没有使用派生类作为参数,泛型参数是某个类的接口。我认为您将它与名为“Curiously Recurring Template Pattern”的可爱混淆了
    • 我认为你是一个混淆它的人:: T 正是引用的行所不允许的,而 CRTP 在 C#、Java 和 Kotlin 中工作得很好。
    • 我添加了另一个段落,这可能会使问题更清楚。
    【解决方案2】:

    它是由 JVM 泛型限制引起的。更多信息,您可以阅读 [这里] (https://docs.oracle.com/javase/tutorial/java/generics/restrictions.html)。

    【讨论】:

    • 那会是哪一个?
    猜你喜欢
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多