Implicit parameter and ClassTag

亡梦爱人 提交于 2019-12-06 11:41:10

问题


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)
}

Compiler says:

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.

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)
}

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...


回答1:


This:

def apply[T: ClassTag](data: T)(implicit ordering: Ordering[T]): T = data

is syntactic sugar for this:

def apply[T](data: T)(implicit evidence: ClassTag[T], ordering: Ordering[T]): T = data

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)
}


来源:https://stackoverflow.com/questions/23718165/implicit-parameter-and-classtag

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!