212
212

Reputation: 985

Creating a new variable in Scala case block?

These two statements behave the same :

def getNum(inp: String): Double = inp match { case "" | null => 0.0 case _ => inp.toDouble }

def getNum(inp: String): Double = inp match { case "" | null => 0.0 case x => x.toDouble }

Question is, where should either one be used and is one essentially better than the other?

Upvotes: 1

Views: 89

Answers (1)

Rex Kerr
Rex Kerr

Reputation: 167901

The bytecode for the two is identical, so you can use whichever you prefer stylistically.

Note that in some cases you may have a complex expression as the source of your value to match, which makes it harder to refer to. Thus you may have greater consistency of style with the case x => x.toDouble form.

Upvotes: 3

Related Questions