簡體   English   中英

使用通配符的 Kotlin 泛型自定義類型

[英]Kotlin Generics custom Type using Wildcard

因此,在 Java 中,我可以執行以下操作,以定義具有超類和接口約束的類型。

public class Main<ControllerType extends Node & Controller> {
    private ControllerType controller;
    private ControllerType controller2;

    private Main(ControllerType controller, ControllerType controller2) {
        this.controller = controller;
        this.controller2 = controller2;
    }

    public static void main(String[] args) {
        Main<?> main = new Main<>(new Home(), new Parent());
    }
}

但在 Kotlin 中這是不可能的。

class Main<ControllerType>(val controller: ControllerType, val controller2: ControllerType)
        where ControllerType : Node, ControllerType : Controller

fun main(args: Array<String>) {
    val main = Main<*>(Home(), Parent())
}

我在星形投影中收到以下錯誤:

不允許對函數和屬性的類型參數進行投影

那么,如何才能解決這個問題。 我查看了類型別名,但它們沒有我想要的功能。

不,沒有辦法像通配符那樣像Java那樣做到這一點。 這是不可能的,因為通配符也不安全。

private Main(ControllerType controller, ControllerType controller2)

controllercontroller2假設是相同的或繼承的類型,但 Java 允許您使用通配符來回避它。

星形投影不是通配符替換。 星形投影是在您不知道確切類型並允許您執行安全操作時使用。

如果controllercontroller2是兩種不同的類型,那么你應該有兩個通用參數。

class Main<T, U>(val controller: T, val controller2: U)
        where T : Node, T : Controller, U : Node, U : Controller

fun main(args: Array<String>) {
    val main = Main(Home(), Parent())
}

該錯誤僅由嘗試在實例創建表達式中使用通配符(投影)引起。 它與交集類型或 Kotlin 無關。

在聲明中

Main<?> main = new Main<>(new Home(), new Parent());

<>不是<?> ,它是<Node>

在 Kotlin 中,同樣的語句是

val main : Main<*> = Main<Node>(Home(), Parent())

或(沒有顯式類型參數)

val main : Main<*> = Main(Home(), Parent())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM