如何处理从Java迁移到Kotlin的泛型边界? [英] How to deal with generic bounds migrating from Java to Kotlin?
问题描述
我的目标是让接口方法接受实现的类类型。这里是我写的代码:
My goal is to have the interface methods accept the class type of the implementation. Here's the code I have written so far:
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>
使用原始类型 差异
。不要这么做!
The reason why this "worked" in Java was because <T extends Diff>
uses the raw type Diff
. Don't do this!
最接近的是使用递归类型绑定:
The closest you can get is to use a recursive type bound:
interface Diff<T : Diff<T>> {
fun lessThan(other: T): Boolean
}
是,您可以替换 Diff
的任何其他子类型。
The problem is, you can substitute any other subtype of Diff
.
但是,当使用 Diff
,使用泛型类型约束 T:Diff< T>
:
However, when using the Diff
, use the generic type constraint T : Diff<T>
:
fun <T : Diff<T>> diffUser(diff1: T, diff2: T) {
println(diff1.lessThan(diff2))
}
和任何 Diff
不会执行 Diff< SameType>
不会被接受。
and any Diff
that doesn't implement Diff<SameType>
will not be accepted.
示例:
Example:
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))
}
同样的方法被可比较的
类。
虽然这个方法可行,但 want是一个自我类型,虽然它在路线图上,但不受支持在某个时候。我相信JetBrains拒绝了这个请求,但是我找不到错误报告。
Although this works, what you really want is a "self type" and this is not supported, although it was on the roadmap at some point. I believe JetBrains denied the request for this, though I cannot find the bug report.
这个答案详细介绍了Java中使用 CRT模式的解决方法,尽管它不一定是安全的。
This answer details a workaround in Java using the CRT pattern, though it is not necessarily type safe.
这篇关于如何处理从Java迁移到Kotlin的泛型边界?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!