Thursday, September 17, 2009

Tuples and the -> implicit method

Defined in the Predef object are several implicit methods. All implicit methods defined in the Predef method are applicable to all programs without importing them. One such method is the -> method. This method is applicable to all objects and creates a Tuple2.

Examples:
  1. // normal way to make a Tuple2
  2. scala> (1,2)
  3. res3: (Int, Int) = (1,2)
  4. // another way to make a Tuple2 using the implicit -> method
  5. scala> 1 -> 2
  6. res2: (Int, Int) = (1,2)
  7. // Creating a map using the normal tuples creation mechanism
  8. scala> Map (("one",1),
  9.      |      ("two",2))
  10. res5: scala.collection.immutable.Map[java.lang.String,Int] = Map(one -> 1, two -> 2)
  11. // -> syntax allows a second "prettier" way of creating the Map
  12. scala> Map("one" -> 1,
  13.      |     "two" -> 2)
  14. res6: scala.collection.immutable.Map[java.lang.String,Int] = Map(one -> 1, two -> 2)

No comments:

Post a Comment