隐式参数和 ClassTag [英] Implicit parameter and ClassTag
问题描述
谁能用下面的错误消息解释 Scala 编译器试图告诉我什么?
Can someone explain what the Scala compiler is trying to tell me with the error message below?
object Some {
def apply[T: ClassTag](data: T)(implicit ordering: Ordering[T]): T = data
}
object Other {
def apply[T: ClassTag](data: T)(implicit ordering: Ordering[T]): T =
Some(data)(ordering.reverse)
}
编译器说:
not enough arguments for method apply: (implicit evidence$2: scala.reflect.ClassTag[T], implicit ordering: Ordering[T])T in object Some. Unspecified value parameter ordering.
当我将 ClassTag
添加到对象 Some
中的方法时出现错误,以便在那里使用一些内部数组.最初,代码是(并且编译时没有错误):
The error arose when I added the ClassTag
to the method in object Some
, in order to use some internal arrays there. Initially, the code was (and compiled without errors):
object Some {
def apply[T](data: T)(implicit ordering: Ordering[T]): T = data
}
object Other {
def apply[T: ClassTag](data: T)(implicit ordering: Ordering[T]): T =
Some(data)(ordering.reverse)
}
我知道 ClassTag
添加了一个隐式的类型信息来克服擦除,但我不明白这与我的排序隐式参数有什么关系,或者为什么编译器突然认为排序没有价值...
I know ClassTag
adds an implicit with type information to overcome erasure, but I don't understand what that has to do with my ordering implicit parameters, or why the compiler suddenly thinks that ordering has no value...
推荐答案
这个:
def apply[T: ClassTag](data: T)(implicit ordering: Ordering[T]): T = data
是用于此的语法糖:
def apply[T](data: T)(implicit evidence: ClassTag[T], ordering: Ordering[T]): T = data
当您明确指定隐式参数时,您必须同时提供它们.您可以使用 implicitly
来继承隐式 ClassTag
:
When you explicitly specify the implicit parameters you must provide both of them. You can use implicitly
to carry over the implicit ClassTag
:
object Other {
def apply[T: ClassTag](data: T)(implicit ordering: Ordering[T]): T =
Some(data)(implicitly, ordering.reverse)
}
这篇关于隐式参数和 ClassTag的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!