无法解析受约束 class 类型参数的隐式
Can't resolve the implicit for a constrained class type parameter
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] ^
Module
需要隐式 List[T]
。您可以为其定义隐式构造函数参数:
object Implicit {
sealed trait A
class B extends A
class C extends A
def listOf[T <: A](implicit ts: List[T]): List[T] = ts
implicit val aList: List[A] = List.empty[A]
implicit val bList: List[B] = List.empty[B]
class Module[T <: A](implicit ts: List[T]) {
listOf[T].toSet
}
}
val x = new Implicit.Module[Implicit.B]
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] ^
Module
需要隐式 List[T]
。您可以为其定义隐式构造函数参数:
object Implicit {
sealed trait A
class B extends A
class C extends A
def listOf[T <: A](implicit ts: List[T]): List[T] = ts
implicit val aList: List[A] = List.empty[A]
implicit val bList: List[B] = List.empty[B]
class Module[T <: A](implicit ts: List[T]) {
listOf[T].toSet
}
}
val x = new Implicit.Module[Implicit.B]