gpt4 book ai didi

generics - 如何处理从 Java 迁移到 Kotlin 的泛型边界?

转载 作者:行者123 更新时间:2023-12-02 13:23:36 25 4
gpt4 key购买 nike

我的目标是让接口(interface)方法接受实现的类类型。这是我到目前为止编写的代码:

internal interface Diff<Diff> {   //in Java I was using <? extends Diff>
fun lessThan(other: Diff): Boolean
}

private class ADiff(private val value: Int) : Diff<ADiff> {

override fun lessThan(other: ADiff): Boolean {
return value < other.value
}

}

//B can now accept even int types which is not desired
private class BDiff(private val value: Int) : Diff<Int> {

override fun lessThan(other: Int): Boolean {
return value < other
}

}

最佳答案

这在 Java 中“有效”的原因是因为 <T extends Diff>使用 raw type Diff .不要这样做!

您可以获得的最接近的是使用递归类型绑定(bind):

interface Diff<T : Diff<T>> {
fun lessThan(other: T): Boolean
}

问题是,您可以替换 Diff 的任何其他子类型。 .

但是,当使用 Diff , 使用泛型类型约束 T : Diff<T> :
fun <T : Diff<T>> diffUser(diff1: T, diff2: T) {
println(diff1.lessThan(diff2))
}

和任何 Diff没有实现 Diff<SameType>将不被接受。

例子:
class CDiff(private val value: Int) : Diff<DDiff> { // <-- Wrong type!
override fun lessThan(other: DDiff) = value < other.value
}

class DDiff(val value: Int) : Diff<DDiff> {
override fun lessThan(other: DDiff) = value < other.value
}

fun test() {
diffUser(CDiff(3), CDiff(4)) // <-- Doesn't compile due to the generic constraint
diffUser(DDiff(3), DDiff(4))
}

This same approachComparable 使用类(class)。

虽然这可行,但你真正想要的是“自我类型” and this is not supported, although it was on the roadmap at some point .我相信 JetBrains 拒绝了这个请求,尽管我找不到错误报告。

This answer详细介绍了使用 the CRT pattern 的 Java 解决方法,尽管它不一定是类型安全的。

关于generics - 如何处理从 Java 迁移到 Kotlin 的泛型边界?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47493467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com