什么是隐式对象? [英] What are implicit objects?
问题描述
我正在阅读有关类型的信息类,其中提到了隐式对象:
I was reading about type classes where implicit objects were mentioned:
object Math {
trait NumberLike[T] {
def plus(x: T, y: T): T
def divide(x: T, y: Int): T
def minus(x: T, y: T): T
}
object NumberLike {
implicit object NumberLikeDouble extends NumberLike[Double] {
def plus(x: Double, y: Double): Double = x + y
def divide(x: Double, y: Int): Double = x / y
def minus(x: Double, y: Double): Double = x - y
}
implicit object NumberLikeInt extends NumberLike[Int] {
def plus(x: Int, y: Int): Int = x + y
def divide(x: Int, y: Int): Int = x / y
def minus(x: Int, y: Int): Int = x - y
}
}
}
它们是什么?他们在哪里描述?我只在网络上找到了隐式类的定义,但是没有对隐式对象的定义. >
What are they? Where are they described? I only found definition of implicit classes on the web but not of implicit objects.
推荐答案
在Scala中,对象和值的处理方式大致相同.可以将隐式对象视为在查找其类型的隐式的过程中发现的值.
In Scala, objects and values are treated mostly the same. An implicit object can be thought of as a value which is found in the process of looking up an implicit of its type.
在您的示例中,如果隐式地查找类型参数为Double
或Int
的NumberLike
类型类,则将找到NumberLikeDouble
和NumberLikeInt
.
In your example, if one implicitly looks for a NumberLike
type class with type parameter Double
or Int
, one will find NumberLikeDouble
and NumberLikeInt
.
implicit object NumberLikeDouble extends NumberLike[Double]
因此与
implicit val NumberLikeDouble: NumberLike[Double] = new NumberLike[Double] { ...}
或
implicit def NumberLikeDouble: NumberLike[Double] = new NumberLike[Double] { ...}
像val
一样,只有一个该类型的值,并且不需要实例化.
Like a val
, there is only a single value of that type and instantiation is not needed.
一个简单的用例:
import Math.NumberLike
def sum[A](x: A, y: A)(implicit nl: NumberLike[A]) = nl.plus(x, y)
sum(4, 5) // finds NumberLikeInt
这篇关于什么是隐式对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!