Play 2.1 Scala 2.10 and String Interpolation

Play Roadmap has been published. The major feature will be the support of scala 2.10 version.

By using Play 2.1 we can start profiting with String interpolation

STRING INTERPOLATION: QUICK EXAMPLE ?

1
2
3
val n = 20

"Bob is "+n+" years old"

can be replaced by :

1
s"Bob is $n years old"

The benefit of using String interpolation are :

  • one or two characters in less
  • compile time check
  • compile time transformation ( thanks to macros)
  • PLAY 2.1

    On Play framework an sample action can be :

    1
    2
    3
    4
    
    def index = Action {
      val version = 2.10
      Ok("hello scala "+ version)
    }
    

    And by String interpolation we can rewrite it as :

    1
    2
    3
    4
    
    def index = Action {
      val version = 2.10
      Ok(s"hello scala $version")
    }
    

    BETTER !

    Let’s do better and remove parenthesizes and ’s’ characters

    First create an implicit class (scala 2.10 features) to wrap a call to Ok object and define an ok object :

    1
    2
    3
    4
    5
    6
    7
    
    implicit class HTTPInterpolation(s: StringContext) {
       object ok {
         def apply(exprs: Any*) = {
           Ok(s.s(exprs: _*))
         }
       }
     }
    

    Now we can use it as

    1
    2
    3
    4
    
    def index = Action {
        val version = 2.10
        ok"hello scala $version"
    }
    

    Short and concise !

    REFERENCES :

  • Play RaodMap: https://docs.google.com/document/d/1OEt6gZ3a-daSkNXqXGAM4jBs5LtuDkLZIzsWN9aeM1g/preview?sle=true.
  • String interpolation : https://docs.google.com/document/d/1NdxNxZYodPA-c4MLr33KzwzKFkzm9iW9POexT9PkJsU/edit
  • Implicit Class : http://docs.scala-lang.org/sips/pending/implicit-classes.html
  • Macro : http://scalamacros.org/
  • String interpolation with concise samples : http://www.blog.project13.pl/index.php/coding/1540/scala-2-10-0-hello-string-interpolation/
  • Comments