本地副本:
/***
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)
}
Run Code Online (Sandbox Code Playgroud)
错误:
[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
Run Code Online (Sandbox Code Playgroud)
如何将单个最后一个元素更改为另一个元素?
Shapeless's Poly实际上只是一种捆绑一些隐式实例的方法,这些实例描述了不同类型应该发生的事情,因此您可以使用Scala中其他情况下使用的相同隐式优先级技巧:
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)
}
Run Code Online (Sandbox Code Playgroud)
这将导致隐式搜索首先检查特定情况,然后才进入默认情况,而不是简单地将其举手,因为如果hlist具有a String或Int元素则模糊不清.
作为旁注,我建议在这里提供显式类型注释:
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)
}
Run Code Online (Sandbox Code Playgroud)
它有点嘈杂,但它可以避免一些烦人和难以调试的问题.
| 归档时间: |
|
| 查看次数: |
150 次 |
| 最近记录: |