无形:隐含在功能体中

时间:2017-10-12 08:16:35

标签: scala shapeless

我有以下代码段:

<K, V>

val reprEncoder: CsvEncoder[String :: Int :: Boolean :: HNil] = implicitly 在这里意味着什么?

1 个答案:

答案 0 :(得分:4)

这意味着:“召唤您在类型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类型的唯一隐含值。请注意,如果在范围编译中有多个相同类型的隐式值,则编译失败并显示错误:“模糊隐式值”。事实上:

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>