Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others


0 votes
in Technique[技术] by (71.8m points)

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

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: 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?.

See Question&Answers more detail:os

Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share