使用 "any of" 而不是 "all of" 的 Kotlin 泛型约束
Kotlin generic constraint with "any of" rather than "all of"
问题:有没有一种方法可以在 Kotlin 中约束泛型类型,使其可以是类型列表的析取或 "whatever has function foo",而不是约束的结合?
where T:Type1, T:Type2<Foo>
表示T必须符合Type1和Type2
但是,例如,如果我想用 sqr 扩展 Math,它在内置数字类型上运行怎么办:
fun <T> Math.sqr(op:T): T
where T:Int or Long or Float or Double = op * op
甚至在具有 *
或 times
的任何东西上:
fun <T> Math.sqr(op:T): T
where T: can do times // like "responds to selector" in Obj-C
= op.times(op)
有类似的吗?
后者更酷,因为 T 可以是 "Complex" 或将“*”定义为其内积的向量……想象并实现。
理论上,我本可以发明一套继承自 "Math-able" 的 "primitives",但这很丑陋,因为这意味着我需要使用我自己的一套变量。
interface Mathable {
fun plus(m:Mathable)
fun minus(m:Mathable)
fun times(m:Mathable)
fun div(m:Mathable)
}
class Int2 : Number, Comparable<Int2>, Mathable
和
一样丑(当然是相对而言...)
inline fun <reified T:Number> sqr(n:T):T {
return where n {
is Int -> n * n
is Float -> n * n
is Whatever -> n * n
....
else -> throw SomeException("huh?!")
}
}
有better/cooler方法吗?
更新:检查 Kotlin class Int
代码,让我怀疑。他们只是通过超载来做到这一点。不过,很高兴知道这是否可行。
谢谢
很遗憾,答案是:
没有,目前没有。
如果被接受,Type classes 提议(或类似的东西)将修复它(类似 Mathable
的东西将是 class 类型)。
even on anything that has *
or times
这称为结构类型,我认为 Kotlin 没有类似的计划。
问题:有没有一种方法可以在 Kotlin 中约束泛型类型,使其可以是类型列表的析取或 "whatever has function foo",而不是约束的结合?
where T:Type1, T:Type2<Foo>
表示T必须符合Type1和Type2
但是,例如,如果我想用 sqr 扩展 Math,它在内置数字类型上运行怎么办:
fun <T> Math.sqr(op:T): T
where T:Int or Long or Float or Double = op * op
甚至在具有 *
或 times
的任何东西上:
fun <T> Math.sqr(op:T): T
where T: can do times // like "responds to selector" in Obj-C
= op.times(op)
有类似的吗? 后者更酷,因为 T 可以是 "Complex" 或将“*”定义为其内积的向量……想象并实现。
理论上,我本可以发明一套继承自 "Math-able" 的 "primitives",但这很丑陋,因为这意味着我需要使用我自己的一套变量。
interface Mathable {
fun plus(m:Mathable)
fun minus(m:Mathable)
fun times(m:Mathable)
fun div(m:Mathable)
}
class Int2 : Number, Comparable<Int2>, Mathable
和
一样丑(当然是相对而言...)inline fun <reified T:Number> sqr(n:T):T {
return where n {
is Int -> n * n
is Float -> n * n
is Whatever -> n * n
....
else -> throw SomeException("huh?!")
}
}
有better/cooler方法吗?
更新:检查 Kotlin class Int
代码,让我怀疑。他们只是通过超载来做到这一点。不过,很高兴知道这是否可行。
谢谢
很遗憾,答案是:
没有,目前没有。
如果被接受,Type classes 提议(或类似的东西)将修复它(类似
Mathable
的东西将是 class 类型)。even on anything that has
*
ortimes
这称为结构类型,我认为 Kotlin 没有类似的计划。