Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

2.3 implicits

998 views

Published on

  • Be the first to comment

  • Be the first to like this

2.3 implicits

  1. 1. Implicit conversions
  2. 2. Magic? String s = "!em esreveR"; System.out.println(s.reverse());val s: java.lang.String = "!em esreveR"println(s.reverse)=> Reverse me!
  3. 3. Magic? String s = "!em esreveR"; System.out.println(s.reverse());val s: java.lang.String = "!em esreveR"println(s.reverse)println(stringWrapper(s).reverse)=> Reverse me!
  4. 4. Magic? String s = "!em esreveR"; System.out.println(s.reverse());val s: java.lang.String = "!em esreveR"println(s.reverse)println(stringWrapper(s).reverse)println(new runtime.RichString(s).reverse)=> Reverse me!
  5. 5. implicitimplicit def stringWrapper(x: String) = new runtime.RichString(x)
  6. 6. scala.runtime.RichStringdef toArray : Array[Char]def toBoolean : Booleandef toByte : Bytedef toDouble : Doubledef toFloat : Floatdef toInt : Intdef toLong : Longdef toShort : Shortdef r : Regexdef lines : Iterator[java.lang.String]def * (n : Int) : java.lang.String...
  7. 7. scala.PredefA set of implicits Other nice functions byteWrapper(x: Byte) shortWrapper(x: Short) println(...) intWrapper(x: Int) charWrapper(c: Char) readLine(...) longWrapper(x: Long) floatWrapper(x: Float) error(...) doubleWrapper(x: Double) ... booleanWrapper(x: Boolean) stringWrapper(x: String) stringBuilderWrapper(x : StringBuilder) ...
  8. 8. Map and ArrowAssocval myMap: Map[Int, String] = Map(1 -> "one", 2 -> "two")
  9. 9. Map and ArrowAssocval myMap: Map[Int, String] = Map(1 -> "one", 2 -> "two") Map.apply(Tuple2(1, "one"), Tuple2(2, "two"))
  10. 10. Map and ArrowAssocval myMap: Map[Int, String] = Map(1 -> "one", 2 -> "two") Map((1, "one"), (2, "two"))
  11. 11. Map and ArrowAssocval myMap: Map[Int, String] = Map(1 -> "one", 2 -> "two") Map(any2ArrowAssoc(1) -> "one", any2ArrowAssoc(2) -> "two") Map((1, "one"), (2, "two"))
  12. 12. scala.Predef.ArrowAssocimplicit def any2ArrowAssoc[A](x: A): ArrowAssoc[A] = new ArrowAssoc(x)class ArrowAssoc[A](x: A) { def -> [B](y: B): Tuple2[A, B] = Tuple2(x, y)}val myMap = Map(1 -> "one", 2 -> "two")
  13. 13. Implicit rules!Marking Rule: Only definitions marked implicit are available.Scope Rule: An inserted implicit conversion must be in scope as a single identifier, or be associated with the source or target type of the conversion.Non-Ambiguity Rule: An implicit conversion is only inserted if there is no other possible conversion to insert.One-at-a-time Rule: Only one implicit is tried.Explicits-First Rule: Whenever code type checks as it is written, no implicits are attempted.

×