我想在kotlin中有一个非泛型类,它在构造函数中使用泛型来指定一个参数.但是,我无法弄清楚如何做到这一点,并且Intellij的Java-to-Kotlin转换器中断了.
我的java类看起来像这样
public class Test {
interface I1 { }
interface I2 { }
private final I1 mI1;
private final I2 mI2;
public <T extends I1 & I2> Test(T host) {
mI1 = host;
mI2 = host;
}
}
Run Code Online (Sandbox Code Playgroud)
转换器的输出如下所示.
class Test(host: T) where T: I1, T: I2 {
internal interface I1
internal interface I2
private val mI1: I1
private val mI2: I2
init {
mI1 = host
mI2 = host
}
}
Run Code Online (Sandbox Code Playgroud)
我想这样做是因为在Android开发中能够指定一个看起来像的构造函数参数是很有用的 <Host extends Context & CustomCallbackInterface>
看看Kotlin的语法,目前看来这是不可能的.对于主构造函数,类型参数表示类类型参数:
Run Code Online (Sandbox Code Playgroud)class (used by memberDeclaration, declaration, toplevelObject) : modifiers ("class" | "interface") SimpleName typeParameters? primaryConstructor? (":" annotations delegationSpecifier{","})? typeConstraints (classBody? | enumClassBody) ;
对于辅助构造函数,没有可能的类型参数:
Run Code Online (Sandbox Code Playgroud)secondaryConstructor (used by memberDeclaration) : modifiers "constructor" valueParameters (":" constructorDelegationCall)? block ;
但是,构造函数只是一个特殊的函数.如果我们不使用构造函数,而是使用我们自己的函数,我们可以提出以下内容:
class Test {
interface I1
interface I2
private val mI1: I1
private val mI2: I2
internal constructor(host: I1, host2: I2) {
mI1 = host
mI2 = host2
}
companion object {
fun <T> create(host: T): Test where T : Test.I1, T : Test.I2 {
return Test(host, host)
}
}
}
fun <T> test(host: T): Test where T : Test.I1, T : Test.I2 {
return Test(host, host)
}
Run Code Online (Sandbox Code Playgroud)
我们现在可以调用Test.create(host)或test(host)创建一个实例.
| 归档时间: |
|
| 查看次数: |
944 次 |
| 最近记录: |