【发布时间】:2021-08-22 19:13:17
【问题描述】:
package ir.ashkan.shahnameh
object Implicit {
sealed trait A
class B extends A
class C extends A
def listOf[T <: A](implicit ts: List[T]): List[T] = ts
class Module[T <: A] {
implicit val bList: List[B] = ???
implicit val cList: List[C] = ???
listOf[T].toSet // HERE
}
}
编译失败:
could not find implicit value for parameter ts: List[T] (No implicit view available from Int => T.)
[error] listOf[T].toSet
[error] ^
【问题讨论】:
-
T可能是Nothing可能是B with C可能是C with A可能是B或C的另一个子类型 - 因此,不能保证会有范围内的隐式List[T]。你能做的最好的就是class Module[T <: A](implicit ev: List[T])并将这两个隐式 val 移动到Module的伴随对象我相信它们应该在隐式范围内。
标签: scala implicit type-parameter