2017-10-12 74 views
-1

我有下面的代碼片段:無形:隱函數體

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

是什麼意思implicitly這裏?

+0

請問在請求文檔之前 – cchantep

+0

我看了看,但無法配置它。那是因爲我在這裏問。 –

+0

'隱式地'定義在這裏:https://github.com/scala/scala/blob/2.12.x/​​src/library/scala/Predef.scala#L187 –

回答

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>