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

只愿长相守 提交于 2019-11-29 15:31:56

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

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!