代码之家  ›  专栏  ›  技术社区  ›  softshipper

无形状:隐含在函数体中

  •  -1
  • softshipper  · 技术社区  · 7 年前

    我有以下代码段:

    val reprEncoder: CsvEncoder[String :: Int :: Boolean :: HNil] =
      implicitly
    

    什么是 implicitly 我是说这里?

    1 回复  |  直到 7 年前
        1
  •  4
  •   lambdista    7 年前

    这意味着:“调用类型范围内的隐式实例 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>