我可以在 Kotlin 中扩展 Comparable<T> 吗?
Can I extend Comparable<T> in Kotlin?
我想为 Kotlin 的 Comparable<T>coerceAtLeast()
/coerceAtMost()
实现 min()
/max()
别名,如果没有别的练习扩展接口(我已经到目前为止只扩展了 类)。
我试过这个:
fun <T>Comparable<T>.max(other:T) : T {
return this.coerceAtLeast(other)
}
但我收到以下错误:
Type inference failed: Cannot infer type parameter T in fun <T : Comparable<T#1 (type parameter of kotlin.ranges.coerceAtLeast)>> T#1.coerceAtLeast(minimumValue: T#1): T#1
None of the following substitutions
receiver: Any? arguments: (Any?)
receiver: Comparable<T#2 (type parameter of com.nelsonirrigation.twig.plans.extensions.max)> arguments: (Comparable<T#2>)
receiver: T#2 arguments: (T#2)
receiver: Comparable<Comparable<T#2>> arguments: (Comparable<Comparable<T#2>>)
can be applied to
receiver: Comparable<T#2> arguments: (T#2)
至此我对Kotlin泛型的有限理解基本溢出。我正在尝试做的事情是可以实现的吗?我缺少的拼图是什么?
您会在 implementation of coerceAtLeast
中注意到扩展函数的声明与您拥有的略有不同:
fun <T : Comparable<T>> T.coerceAtLeast(minimumValue: T): T
如果您更改声明以匹配,它会编译。
归结为minimumValue
的类型问题。在您的版本中,minimumValue
的类型未强制执行 Comparable<T>
,因此它无法将您的 other
强制转换为符合 coerceAtLeast
约定的类型。
请注意,可以直接在接口上编写扩展函数,这是调用另一个与您的键入配置不匹配的方法导致此中断的结果。
我想为 Kotlin 的 Comparable<T>coerceAtLeast()
/coerceAtMost()
实现 min()
/max()
别名,如果没有别的练习扩展接口(我已经到目前为止只扩展了 类)。
我试过这个:
fun <T>Comparable<T>.max(other:T) : T {
return this.coerceAtLeast(other)
}
但我收到以下错误:
Type inference failed: Cannot infer type parameter T in fun <T : Comparable<T#1 (type parameter of kotlin.ranges.coerceAtLeast)>> T#1.coerceAtLeast(minimumValue: T#1): T#1
None of the following substitutions
receiver: Any? arguments: (Any?)
receiver: Comparable<T#2 (type parameter of com.nelsonirrigation.twig.plans.extensions.max)> arguments: (Comparable<T#2>)
receiver: T#2 arguments: (T#2)
receiver: Comparable<Comparable<T#2>> arguments: (Comparable<Comparable<T#2>>)
can be applied to
receiver: Comparable<T#2> arguments: (T#2)
至此我对Kotlin泛型的有限理解基本溢出。我正在尝试做的事情是可以实现的吗?我缺少的拼图是什么?
您会在 implementation of coerceAtLeast
中注意到扩展函数的声明与您拥有的略有不同:
fun <T : Comparable<T>> T.coerceAtLeast(minimumValue: T): T
如果您更改声明以匹配,它会编译。
归结为minimumValue
的类型问题。在您的版本中,minimumValue
的类型未强制执行 Comparable<T>
,因此它无法将您的 other
强制转换为符合 coerceAtLeast
约定的类型。
请注意,可以直接在接口上编写扩展函数,这是调用另一个与您的键入配置不匹配的方法导致此中断的结果。