Monday, August 3, 2009

Strings

Beginner tip:

Scala has a built-in implicit conversion from java.lang.String to scala.runtime.RichString. Here are some things you can try:
  1. scala>val s = "hi"
  2. s: java.lang.String = hi
  3. scala> s.length 
  4. res0: Int = 2
  5. scala> s(1)
  6. res1: Char = i
  7. scala> s(0)
  8. res2: Char = h
  9. scala> s.r 
  10. res3: scala.util.matching.Regex = hi
  11. scala> s.drop(1)
  12. res4: scala.runtime.RichString = i
  13. scala> s.take(1)
  14. res5: scala.runtime.RichString = h
  15. scala>val longString = """
  16.      | second line
  17.      | third line
  18.      | """
  19. longString: java.lang.String = 
  20.        second line
  21.        third line
  22.        
  23. scala> longString.lines
  24. res6: Iterator[String] = non-empty iterator
  25. scala> longString.lines.toList
  26. res7: List[String] = List(,        second line,        third line,        )
  27. scala> longString.lines.map( _.length )
  28. res8: Iterator[Int] = non-empty iterator

No comments:

Post a Comment