Shapeless:隐含在函数体中
Shapeless: Implicitly in the function body
我有以下代码片段:
val reprEncoder: CsvEncoder[String :: Int :: Boolean :: HNil] =
implicitly
这里的implicitly
是什么意思?
表示:"summon the implicit instance that you have in scope for the type CsvEncoder[String :: Int :: Boolean :: HNil]
"。下面这个简单的例子,在 Scala REPL 会话中,应该很清楚:
$ scala
Welcome to Scala 2.12.3 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_144).
Type in expressions for evaluation. Or try :help.
scala> implicit val str: String = "hello"
str: String = hello
scala> val anotherStr: String = implicitly
anotherStr: String = hello
如您所见,分配给 anotherStr
的值是 str
的值,这是范围内类型 String
的唯一隐式值。请注意,如果您在作用域中有多个相同类型的隐式值,编译将失败并显示错误:"ambiguous implicit values"。确实:
scala> implicit val str: String = "hello"
str: String = hello
scala> implicit val str2: String = "world"
str2: String = world
scala> val anotherStr: String = implicitly
<console>:16: error: ambiguous implicit values:
both value StringCanBuildFrom in object Predef of type =>
scala.collection.generic.CanBuildFrom[String,Char,String]
and method $conforms in object Predef of type [A]=> A <:< A
match expected type T
val anotherStr: String = implicitly
^
scala>
我有以下代码片段:
val reprEncoder: CsvEncoder[String :: Int :: Boolean :: HNil] =
implicitly
这里的implicitly
是什么意思?
表示:"summon the implicit instance that you have in scope for the type CsvEncoder[String :: Int :: Boolean :: HNil]
"。下面这个简单的例子,在 Scala REPL 会话中,应该很清楚:
$ scala
Welcome to Scala 2.12.3 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_144).
Type in expressions for evaluation. Or try :help.
scala> implicit val str: String = "hello"
str: String = hello
scala> val anotherStr: String = implicitly
anotherStr: String = hello
如您所见,分配给 anotherStr
的值是 str
的值,这是范围内类型 String
的唯一隐式值。请注意,如果您在作用域中有多个相同类型的隐式值,编译将失败并显示错误:"ambiguous implicit values"。确实:
scala> implicit val str: String = "hello"
str: String = hello
scala> implicit val str2: String = "world"
str2: String = world
scala> val anotherStr: String = implicitly
<console>:16: error: ambiguous implicit values:
both value StringCanBuildFrom in object Predef of type =>
scala.collection.generic.CanBuildFrom[String,Char,String]
and method $conforms in object Predef of type [A]=> A <:< A
match expected type T
val anotherStr: String = implicitly
^
scala>