小编典典

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

javascript

我不明白当作为隐式参数传递时会发生什么。(我想我一般理解隐式参数的概念)。Integral[T]

让我们考虑这个函数

import scala.math._

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

现在我调用fooREPL:

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

integral论点如何变成scala.math.Numeric$IntIsIntegraland scala.math.Numeric$LongIsIntegral


阅读 212

收藏
2022-03-21

共1个答案

小编典典

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

当你传入 anInt时,它会寻找一个隐含对象 anIntegral[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相同的方式工作。

2022-03-21