首页 > 解决方案 > Kotlin 通用约束与“任何”而不是“全部”

问题描述

问题:有没有一种方法可以约束 Kotlin 中的泛型类型,使其可以是类型列表的析取,或者“具有函数 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

甚至在任何具有*or的东西上times

fun <T> Math.sqr(op:T): T
    where T: can do times // like "responds to selector" in Obj-C
    = op.times(op)

有这样的吗?后者更酷,因为 T 可以是“复数”或将“*”定义为其内积的向量……只需想象并实现即可。

从理论上讲,我本可以发明一组继承自“Math-able”的“原语”,但这很丑陋,因为这意味着我需要使用自己的一组变量。

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?!")
    }
}

有没有更好/更酷的方法?

更新:检查 Kotlinclass Int代码让我怀疑。他们只是通过超载来做到这一点。不过,很高兴知道这是否可能。

谢谢

标签: genericskotlinwhere-clause

解决方案


不幸的是,答案是:

  1. 不,目前没有。

  2. 如果被接受,类型类提案(或类似的东西)将修复它(类似于Mathable类型类的东西)。

  3. 即使在任何有*times

    这被称为结构类型,我不认为 Kotlin 计划有任何类似的东西。


推荐阅读