【问题标题】:Constructors for typealiased types using generics使用泛型的类型别名类型的构造函数
【发布时间】:2017-08-04 17:54:45
【问题描述】:

我现在正在学习 Kotlin。

但是我在下面的例子中遇到了问题。

当我键入我自己创建的类的别名时,我可以使用如下所示的普通构造函数,但我不能对 Kotlin 列表类型做同样的事情。我在这里想念什么?

class Example<T> {}

typealias Ex<T> = Example<T> // typealias for example class
typealias L<T> = List<T> // typealias for Kotlin list class

fun main(args: Array<String>) {
    Ex<Int>() // OK! compiles
    L<Int>(0,{ _ -> 1}) // unresolved reference
}

【问题讨论】:

    标签: generics kotlin type-alias


    【解决方案1】:

    这是因为List&lt;T&gt; 是一个接口,这意味着没有构造函数。 typealias 关键字用于现有类型。实际上,List(size,init)stdlib 中被定义为顶级扩展函数,如下所示:

    //             v--- List(size){...} is a function rather than a type
    inline fun <T> List(size:Int, init: (index: Int)->T):List<T>=MutableList(size,init)
    

    如果你把别名L改成concreteArrayList,你发现你也可以使用它的构造函数来创建它,例如:

    typealias L<T> = ArrayList<T> 
    
    fun main(args: Array<String>) {
        // v--- create `L<Int>` by its constructor
        L<Int>(1)
    }
    

    【讨论】:

    • 谢谢,我以为它是一个类而不是一个接口。我不知道可以创建一个看起来像构造函数的函数
    • @TobiahLissens 一点也不。很高兴它帮助了你,:)
    猜你喜欢
    • 2017-03-12
    • 1970-01-01
    • 2010-10-16
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-20
    相关资源
    最近更新 更多