1

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

4

2 回答 2

3

有关shapeless.Replacer实际元素类型的信息应该在编译时可用。Bibbyin 中没有 type的元素Bibbies,所以没有什么可以替换的。

您应该使用泛型类型b,并且还应该Replacer[Bibbies, B, B]像这样添加 required 作为隐式参数:

def update[B <: Bibby](b: B, bibbies: Bibbies)(implicit r: Replacer[Bibbies, B, B]) =
  bibbies.updatedElem(b)

update(LittleBibby(3), defaultBibbies)
// LittleBibby(3) :: BigBibby(beep) :: HNil
于 2014-02-05T18:47:46.767 回答
1

丢弃了有关 bibby 是 little bibby 还是 big 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
于 2014-02-05T18:45:24.343 回答