开发者

How does ‘1 * BigInt(1)’ work and how can I do the same?

开发者 https://www.devze.com 2023-04-10 19:18 出处:网络
I try to implement some number type and I hit the issue that mynum * 1 works, but not 1 * mynum I tried to define an implicit conversion like this

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

mynum * 1

works, but not

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: 开发者_C百科Short)Int <and>
  (x: Byte)Int
 cannot be applied to (Num)
              1 * new Num(2)
                ^

On the other hand

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?

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


When an application a.meth(args) fails, the compiler searches for an implicit view from a to something that has the method meth. Any implicit value or method that conforms to A => { def meth(...) } will do. If one is found, the code is rewritten as view(a).meth(args).

Where does it look? First it looks in the current scope, made up of locally defined implicits, and imported implicits.

(There is actually a second phase of the search, in which conversion methods with by-name arguments are considered, but that's not really important to this answer.)

If this fails, it looks in the implicit scope. This consists of the companion objects of the 'parts' of the type that we're searching for. In this case, we're after A => { def meth(...) }, so we just look at the companion object of A (and its super types).

In Scala trunk, the implicit scope is extended a tiny bit, to include the companion objects of the types of the arguments. Not sure if that was already in 2.9.1, perhaps a friendly reader will figure that out for me and update this answer.

So 1 + BigInt(2) is expanded to BigInt.int2bigInt(1) + BigInt(2)


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号