使用默认值映射HList

时间:2016-09-30 15:22:56

标签: scala shapeless

http://scastie.org/22713

本地副本:

/***
scalaVersion := "2.11.8"
addCompilerPlugin("org.spire-math" %% "kind-projector" % "0.7.1")
libraryDependencies ++= {
  val shapelessVersion = "2.2.5"
  Seq(
    "com.chuusai" %% "shapeless" % shapelessVersion
  )
}
*/

import shapeless._

case class Foo()

trait Wrapper

case class S(s: String) extends Wrapper
case class I(i: Int) extends Wrapper

object Main extends App {
  object wrap extends Poly1 {
    implicit def caseString = at[String](S.apply)
    implicit def caseInt = at[Int](I.apply)
    implicit def caseOther[T] = at[T](identity)
  }

  type A = Foo :: String :: HNil
  type B = Foo :: Int :: HNil
  type Out = Foo :: Wrapper :: HNil

  val a: A = Foo() :: "foo" :: HNil
  val b: B = Foo() :: 42 :: HNil

  val aw: Out = a.map(wrap)
  val bw: Out = b.map(wrap)

}

错误:

[error] /tmp/renderercqsCBmArxo/src/main/scala/test.scala:56: could not find implicit value for parameter mapper: shapeless.ops.hlist.Mapper[Main.wrap.type,Main.A]
[error]   val aw: Out = a.map(wrap)
[error]                      ^
[error] /tmp/renderercqsCBmArxo/src/main/scala/test.scala:57: could not find implicit value for parameter mapper: shapeless.ops.hlist.Mapper[Main.wrap.type,Main.B]
[error]   val bw: Out = b.map(wrap)
[error]                      ^
[error] two errors found
[error] (compile:compileIncremental) Compilation failed

如何将单个最后一个元素更改为另一个元素?

1 个答案:

答案 0 :(得分:5)

Shapeless的Poly实际上只是一种捆绑一些隐式实例的方法,这些实例描述了不同类型应该发生什么,所以你可以使用你在其他情况下使用的相同的隐式优先级技巧在斯卡拉:

object wrap extends LowPriorityWrapCases {
  implicit val caseString = at[String](S.apply)
  implicit val caseInt = at[Int](I.apply)
}

trait LowPriorityWrapCases extends Poly1 {
  implicit def caseOther[T] = at[T](identity)
}

这将导致隐式搜索首先检查特定情况,然后才会进入默认情况,而不是简单地将其举手,因为如果hlist有StringInt则模糊不清元件。

作为旁注,我建议在此提供明确的类型注释:

object wrap extends LowPriorityWrapCases {
  implicit val caseString: Case.Aux[String, S] = at[String](S.apply)
  implicit val caseInt: Case.Aux[Int, I] = at[Int](I.apply)
}

trait LowPriorityWrapCases extends Poly1 {
  implicit def caseOther[T]: Case.Aux[T, T] = at[T](identity)
}

它有点吵,但它可以帮助您避免一些烦人且难以调试的问题。