2017-10-12 4 views
-1

Je extrait de code suivant:Shapeless: Implicitement dans le corps de la fonction

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

Qu'est-ce que implicitly signifie ici?

+0

S'il vous plaît avoir alook à la documentation avant de demander – cchantep

+0

Je l'ai regardé, mais je ne pouvais pas le configurer. Parce que je demandais ici. –

+0

'implicitement' est défini ici: https://github.com/scala/scala/blob/2.12.x/src/library/scala/Predef.scala#L187 –

Répondre

4

Cela signifie: "invoque l'instance implicite dont vous avez la portée pour le type CsvEncoder[String :: Int :: Boolean :: HNil]". L'exemple simple suivant, dans une session REPL Scala, devrait indiquer clairement:

$ 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 

Comme vous pouvez le voir la valeur attribuée à anotherStr est celle de str qui est la seule valeur implicite de type String portée. Notez que si vous avez plus d'une valeur implicite du même type dans la compilation de portée échouera avec l'erreur: "valeurs implicites ambiguës". En effet:

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>