将scala.math.Integral作为隐式参数传递 [英] Passing scala.math.Integral as implicit parameter
问题描述
我已经阅读了关于Integral[T]
是作为隐式参数传递. (我认为我一般理解隐式参数的概念.)
I have read the answer to my question about scala.math.Integral but I do not understand what happens when Integral[T]
is passed as an implicit parameter. (I think I understand the implicit parameters concept in general).
让我们考虑一下这个功能
Let's consider this function
import scala.math._
def foo[T](t: T)(implicit integral: Integral[T]) { println(integral) }
现在我在REPL中呼叫foo
:
Now I call foo
in REPL:
scala> foo(0)
scala.math.Numeric$IntIsIntegral$@581ea2
scala> foo(0L)
scala.math.Numeric$LongIsIntegral$@17fe89
integral
参数如何变为scala.math.Numeric$IntIsIntegral
和scala.math.Numeric$LongIsIntegral
?
推荐答案
参数为implicit
,这意味着Scala编译器将查找是否可以在某个可以自动填充该参数的地方找到隐式对象.
The parameter is implicit
, which means that the Scala compiler will look if it can find an implicit object somewhere that it can automatically fill in for the parameter.
传入Int
时,它将查找作为Integral[Int]
的隐式对象,并在scala.math.Numeric
中找到它.您可以查看scala.math.Numeric
的源代码,在其中:
When you pass in an Int
, it's going to look for an implicit object that is an Integral[Int]
and it finds it in scala.math.Numeric
. You can look at the source code of scala.math.Numeric
, where you will find this:
object Numeric {
// ...
trait IntIsIntegral extends Integral[Int] {
// ...
}
// This is the implicit object that the compiler finds
implicit object IntIsIntegral extends IntIsIntegral with Ordering.IntOrdering
}
同样,Long
有一个不同的隐式对象,其工作方式相同.
Likewise, there is a different implicit object for Long
that works the same way.
这篇关于将scala.math.Integral作为隐式参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!