将scala.math.Integral作为隐式参数传递 [英] Passing scala.math.Integral as implicit parameter

查看:72
本文介绍了将scala.math.Integral作为隐式参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了关于问题的答案://www.scala-lang.org/api/current/scala/math/Integral.html"rel =" noreferrer> scala.math.Integral ,但我不明白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$IntIsIntegralscala.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆