Kotlin Infix功能带有仿制药
尝试编写一个简单的Kotlin Infix函数以进行加操作。通用类型怎么了?
infix fun <T : Number> T.myPlus(that: T): T = this + that
Try to write a simple Kotlin infix function for plus operation. What's wrong with generic type?
infix fun <T : Number> T.myPlus(that: T): T = this + that
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正如其他人提到的那样,由于各种原因,没有使用仿制药的解决方案。您必须为每种数字类型(字节,短,int,long,float,double)定义一个扩展功能。例如,您可以这样做:
即使这样做,在某些情况下,您还需要决定是否要截断或围绕结果。
这种情况(n1是长的,n2是浮点)可以像这样处理:
导致
12330000000000000123
,或者可以这样处理:
导致
1.23E18
中。As others have mentioned, there's no solutions using generics for various reasons. You have to define an extension function for each Number type (Byte, Short, Int, Long, Float, Double). E.g. for Int you could do:
Even doing that, in some cases you need to decide whether you want to truncate or round the result.
This case (n1 is a Long, n2 is a Float) could be handled like this:
resulting in
1230000000000000123
or it could be handled like this:
resulting in
1.23E18
您忘记了运算符关键字:infix运算符fun t.plus(that:t):t = t = this + tht thatedit:
You forgot the operator keyword:infix operator fun T.plus(that: T): T = this + thatEdit:
更多的铸造安全性:
上述。示例args:
没有例外和错误结果。
A bit more casting safety:
In prev. example args:
No exception and wrong result.
您必须找到结果的正确类型:
You have to find the correct type of the result: