问:在kotlin中有没有一种方法可以约束泛型类型,它可以是类型列表的析取,或者“whatever has function foo”,而不是约束的连接?
where T:Type1, T:Type2<Foo>
表示t必须符合类型1和类型2
但是,如果我想用sqr扩展数学,它对内置的数值类型进行操作:
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可以是一个“复数”或向量,“*”定义为它们的内积…想象并实施。
理论上,我本可以发明一组继承自“数学能力”的“原语”,但这相当难看,因为这意味着我需要使用自己的一组变量。
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?!")
}
}
有更好/更酷的方法吗?
更新:检查kotlin
class Int
密码,让我怀疑。他们只是在超载的情况下做的。不过,很高兴知道这是否可能。
谢谢