定义无形替换器

时间:2014-02-05 17:39:12

标签: scala shapeless

我想知道如何使用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的解决方案,但无济于事:/

2 个答案:

答案 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