generics - 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
代码让我怀疑。他们只是通过超载来做到这一点。不过,很高兴知道这是否可能。
谢谢
解决方案
不幸的是,答案是:
不,目前没有。
如果被接受,类型类提案(或类似的东西)将修复它(类似于
Mathable
类型类的东西)。即使在任何有
*
或times
这被称为结构类型,我不认为 Kotlin 计划有任何类似的东西。
推荐阅读
- java - 如何递归地找到直方图中的最大矩形区域?
- javascript - Ramda 合并两个对象关系设备
- node.js - 摩卡,超时后转到下一个文件
- javascript - LocalStorage 变量自动消失
- excel - VBA 或函数将 2x CSV 文件连接到 1x XLSX
- javascript - 如何将字符串转换为布尔表达式?
- amazon-dynamodb - 如何使用 aws cli 仅获取 dynamoDB 中的主键值列表?
- java - 如何使用 JPA 或 Hibernate @JoinTable 与额外的连接条件,如 SQL => from a join b on a.no = b.no 或 b.no 为 null
- c - 是 char str1[] = {'s','t','r','i','n','g','\0'} 从常量内存段复制到堆栈,如 char str2[] = "细绳”?
- c# - C++ & C# 调用 CryptEncrypt 和 CryptDecrypt