你可以在Kotlin中有一个通用的主构造函数吗? [英] Can you have a generic primary constructor in Kotlin?

查看:77
本文介绍了你可以在Kotlin中有一个通用的主构造函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  class Generic< T,R>(thingy:R)
{
val x = thingy.getX()
}

但参数 R 应该不是类签名的一部分。这只在施工时才有意义。



然而,这是行不通的:



$ $ $
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $'

两者都不是:

  class Generic< T>< R>(thingy:R)
{
val x = thingy.getX()
}

并且我在 documentation

解决方案



然而,您可以通过使用工厂方法来获得所需的结果:

 接口HasX< ;出V> {
val x:V
}

class Generic< T>(val x:Int){
伴随对象{
fun< T, R:HasX< Int>> create(thingy:R)= Generic< T>(thingy.x)
}
}

val结果:Generic< String> = Generic.create(object:HasX< Int> {
override val x:Int = 12
})

通常工厂方法以小写开头(例如 mutableList ),没有什么能阻止您以不同的方式进行:

  fun< T,X:HasX< Int>>通用(thingy:X):通用< T> = Generic(thingy.x)

val结果:Generic< String> =通用(对象:HasX< Int> {
覆盖val x:Int = 12
})

正如 @Alexey Romanow 中提到的Kotlin stdlib的一部分,使用这种方法


This would work:

class Generic<T, R>(thingy: R)
{
    val x = thingy.getX()
}

But the parameter R should really not be a part of the class signature. It is relevant only at construction time. The same way a type parameter of a generic method has nothing to do with the type parameters of the class.

However, this does not work:

class Generic<T>(thingy: R)
{
    val x = thingy.getX()
}

neither does this:

class Generic<T><R>(thingy: R)
{
    val x = thingy.getX()
}

and I did not find the answer in the documentation.

解决方案

That is not possible directly.

You can however achieve a desired result by using a factory method:

interface HasX<out V> {
    val x: V
}

class Generic<T>(val x: Int) {
    companion object {
        fun <T, R : HasX<Int>> create(thingy: R) = Generic<T>(thingy.x)
    }
}

val result: Generic<String> = Generic.create(object : HasX<Int> {
    override val x: Int = 12
})

Typically factory methods start with lower case ( e.g. mutableList) there is nothing stopping you from doing it differently:

fun <T, X : HasX<Int>> Generic(thingy: X):Generic<T> = Generic(thingy.x)

val result: Generic<String> = Generic(object : HasX<Int> {
    override val x: Int = 12
})

As noted by @Alexey Romanow parts of the Kotlin stdlib use this approach.

这篇关于你可以在Kotlin中有一个通用的主构造函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆