我想知道如何使用Shapeless库修复此Scala代码,以便编译:
object boo {
import shapeless._
sealed trait Bibby
case class LittleBibby(i: Int) extends Bibby
case class BigBibby(s: String) extends Bibby
type Bibbies = LittleBibby :: BigBibby :: HNil
val defaultBibbies: Bibbies = LittleBibby(1) :: BigBibby("beep") :: HNil
def update(b: Bibby, bibbies: Bibbies) : Bibbies = bibbies.updatedElem(b)
val demo: Bibbies = update(LittleBibby(3), defaultBibbies)
}
我收到以下错误消息:
could not find implicit value for parameter replacer:shapeless.Replacer[boo.Bibbies,boo.Bibby,boo.Bibby]
def update(b: Bibby, bibbies: Bibbies) : Bibbies = bibbies.updatedElem(b)
我试图通过无形的源代码来查找创建缺失的隐式Replacer
的解决方案,但无济于事:/
答案 0 :(得分:3)
对于shapeless.Replacer
,有关实际元素类型的信息应该在编译时可用。 <{1}}中没有Bibby
类型的元素,因此无需替换。
您应该为Bibbies
使用通用类型,并且还应该将必需的b
添加为隐式参数,如下所示:
Replacer[Bibbies, B, B]
答案 1 :(得分:1)
你丢弃关于bibby是bibby还是大毕比的信息:
def update(b: Bibby, bibbies: Bibbies) : Bibbies
我不知道这是否足够,但我首先要保留bibby类型:
def update[T <: Bibby](b: T, bibbies: Bibbies) : Bibbies
然后,您应该添加一个隐式Replacer
参数(如错误消息所示):
def update[T <: Bibby](b: T, bibbies: Bibbies)
(implicit ev: Replacer[Bibbies, T, T]): Bibbies