Search code examples
scalascalatest

scala () vs {} definition of parameter invocation


In the Coursera course "Functional Programming Principles in Scala" Week 1 sample assignment (https://www.coursera.org/learn/progfun1/programming/xIz9O/example-assignment) Martin Ordersky mentions in one of his comments (on line 44 of the ListsSuites.scala test) that

   * In Scala, it is allowed to pass an argument to a method using the block
   * syntax, i.e. `{ argument }` instead of parentheses `(argument)`.

So when assigning a function definition in Scala would it be equivalent to say:

def foo = ()

and

def foo = {}

Solution

  • {} or ({}) refers to block of code.

    {
      statement1
      statement2
      statement3
    }
    

    and the last statement would be returned.

    scala> val x = { 
         |  val x = 4 
         |  x + 1
         | }
    x: Int = 5
    

    While () is for one line expression.

    When are {} and () interchangeable

    1.invoking a method with one param

    scala> def printlnme(x: String) = { println(x)}
    printlnme: (x: String)Unit
    
    scala> printlnme("using parenthesis")
    using parenthesis
    
    scala> printlnme{"using braces"}
    using braces
    

    Not with a method with multiple params,

    scala> def add(x: Int, y: Int) = { x + y }
    add: (x: Int, y: Int)Int
    
    //can also be (x + y) because one line expression
    //scala> def add(x: Int, y: Int) = ( x + y )
    //add: (x: Int, y: Int)Int
    
    scala> add(1, 2)
    res3: Int = 3
    
    scala> add{1, 2}
    <console>:1: error: ';' expected but ',' found.
    foo{1, 2}
         ^
    

    2.one line expression

    In this example I'm only printing the input.

    scala> List(1, 2, 3).foreach { x => println(x) }
    1
    2
    3
    
    scala> List(1, 2, 3).foreach ( x => println(x) )
    1
    2
    3
    

    Or, say one line map function.

    scala> List(1, 2, 3) map { _ * 3}
    res11: List[Int] = List(3, 6, 9)
    
    scala> List(1, 2, 3) map ( _ * 3 )
    res12: List[Int] = List(3, 6, 9)
    

    But () alone can not be used with multiline statements

    scala> :paste
    
    List(1, 2, 3) foreach ( x =>
         val y = x * 28
         println(y)
    )
    
    <console>:2: error: illegal start of simple expression
         val y = x * 28
         ^
    

    you still need ({}) to be able to use parenthesis for multiline.

    scala> :paste
    
    List(1, 2, 3) foreach ( x => {
         val y = x * 28
         println(y)
    })
    
    28
    56
    84