将scala.math.Integral作为隐式参数传递

时间:2011-04-01 10:56:27

标签: scala implicit

我已阅读question关于scala.math.Integral的答案,但我不明白将Integral[T]作为隐式参数传递时会发生什么。 (我想我一般都理解隐式参数概念。)

让我们考虑一下这个功能

import scala.math._

def foo[T](t: T)(implicit integral: Integral[T]) { println(integral) }

现在我在REPL中调用foo

scala> foo(0)  
scala.math.Numeric$IntIsIntegral$@581ea2
scala> foo(0L)
scala.math.Numeric$LongIsIntegral$@17fe89

integral参数如何成为scala.math.Numeric$IntIsIntegralscala.math.Numeric$LongIsIntegral

2 个答案:

答案 0 :(得分:27)

答案 1 :(得分:12)

参数是implicit,这意味着Scala编译器会查看是否可以在某个地方找到一个可以自动填充参数的隐式对象。

当您传入Int时,它会查找一个Integral[Int]的隐式对象,并在scala.math.Numeric中找到它。您可以查看scala.math.Numeric的源代码,您可以在这里找到:

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有一个不同的隐含对象,其工作方式相同。

相关问题