cosmir17
cosmir17

Reputation: 57

Scala pattern matching double curly brackets

I am not sure that this might is a Scala pattern matching question. I saw the following examples and it uses Scala pattern matching.

def sum(ints: List[int]): Int = ints match {
  case Nil => 0
}

def sum(ints: List[int]): Int {
  ints match {
    case Nil => 0
  }
}

what's the difference between these two examples?

Thank you :)

Upvotes: 1

Views: 921

Answers (2)

Curly braces are the way Scala uses to glue together a group of expressions into one whose result is the result of the last expression in the block.

e.g:

{
    val x = 3
    x*2
}

Is an expression whose result is 6.

Writing a single expression within curly braces is redundant and would only make sense for aesthetic purposes.

Going back to your pattern matching:

ints match {
  case Nil => 0
}

Is an expression as any other so you can write it within curly braces or not.

{
    ints match {
      case Nil => 0
    }
}

Scala lets you define your methods body as a group of expressions:

def methodName(params...) { exp0; exp1; .., resExp } // Return type will be Unit.

NOTE That Scala's type inference will determine methodName return type as Unit.

Or as = with an expression at its right side, which could also be a group of expressions this way glued by curly braces.

def methodName(params...): Type = expression
def methodName(params...) = expression //Return type will be the expression's type.

So you can write it in these 3 forms:

// `=` with a single expression at is right side.
def sum(ints: List[Int]): Int = ints match {
  case Nil => 0
}

// `=` with a glued sequence of expressions at is right side.
def sum(ints: List[Int]): Int = {
    ints match {
      case Nil => 0
    }
}

// A glued sequence of expressions at is right side, but its return type will be Unit!
def sum(ints: List[Int]) {
    ints match {
      case Nil => 0
    }
}

Upvotes: 1

Nagarjuna Pamu
Nagarjuna Pamu

Reputation: 14825

In Scala if you are doing pattern matching as the first expression inside a function, you can write the syntax in two ways, but they are equivalent.

Note: here we are starting directly with pattern matching:

def toInt(optStr: Option[String]): Option[Int] = optStr match {
 case Some(str) = Some(str.toInt)
 case None =>  None
}

Another way to put it is that you are doing same thing inside multiline brackets.

 def toInt(optStr: Option[String]): Option[Int] = {
  //same pattern matching inside multiline brackets
  optStr match {
    case Some(str) = Some(str.toInt)
    case None => None
  }

}

Upvotes: 1

Related Questions