"1 * BigInt(1)"如何工作,我该怎么做? [英] How does ‘1 * BigInt(1)’ work and how can I do the same?

查看:90
本文介绍了"1 * BigInt(1)"如何工作,我该怎么做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试实现某种数字类型,但遇到了这个问题

I try to implement some number type and I hit the issue that

mynum * 1

可以,但是不能

1 * mynum

我试图定义这样的隐式转换

I tried to define an implicit conversion like this

case class Num(v: Int) {
  def * (o: Int) = new Num(v*o)
}

implicit def int2Num(v: Int) = Num(v)

但是它似乎没有用,因为我总是会遇到以下错误:

but it doesn't seem work, because I always get the following error:

scala> 1 * new Num(2)
<console>:14: error: overloaded method value * with alternatives:
  (x: Double)Double <and>
  (x: Float)Float <and>
  (x: Long)Long <and>
  (x: Int)Int <and>
  (x: Char)Int <and>
  (x: Short)Int <and>
  (x: Byte)Int
 cannot be applied to (Num)
              1 * new Num(2)
                ^

另一方面

1 * BigInt(1)

有效,因此尽管我在查看代码时无法确定解决方案,但必须有一种方法.

works, so there has to be a way although I couldn't identify the solution when looking at the code.

使其运作的机制是什么?

What's the mechanism to make it work?

我用遇到的实际问题创建了一个新问题,

I created a new question with the actual problem I hit, Why is the implicit conversion not considered in this case with generic parameters?.

推荐答案

我认为您在Num类中缺少*方法,该方法接受Num作为参数.

I think you are missing * method in your Num class which accepts a Num as an argument.

这篇关于"1 * BigInt(1)"如何工作,我该怎么做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆