José Villacreses
José Villacreses

Reputation: 177

Is there a more succint way to express this if expression in scala

I'm just exploring scala. Is there a more succint and/or more idiomatic way to write the following code?

def getValToAdd(c: Char): Int = {
  if ('(' == c) {
    1
  } else if (')' == c) {
    -1
  } else {
    0
  }
}

Upvotes: 0

Views: 65

Answers (2)

Boris the Spider
Boris the Spider

Reputation: 61198

You can remove all of your curly brackets, they're redundant:

def getValToAdd(c: Char): Int =
  if ('(' == c) 1
  else if (')' == c) -1
  else 0

But a much more idiomatic way is to use Pattern Matching

def getValToAdd(c: Char): Int = c match {
  case '(' => 1
  case ')' => -1
  case _ => 0  
}

You can also drop the return type, the compiler can work it out:

def getValToAdd(c: Char) = c match {
  case '(' => 1
  case ')' => -1
  case _ => 0  
}

But I wouldn't recommend that unless this is a private utility method.

Upvotes: 4

Lee
Lee

Reputation: 144206

def getValToAdd(c: Char): Int = c match {
    case '(' => 1
    case ')' => -1
    case _ => 0
}

Upvotes: 0

Related Questions