Scala If Else Expression with Example Code

Scala If Else control structure has used syntax and usage as Java if else. If Else in Scala is used as an expression rather than a control structure because if..else in Scala returns a value. Here I have tried to give you more details and code examples of Scala If Else Expression.

Scala If Else Expression
Scala If Else Expression
Expression Syntax
var variable = if (boolean) expression
var variable = if (boolean) expression else expression
var variable = if (boolean) expression else if (boolean) expression ... 
var variable = if (boolean) expression else if (boolean) expression ... else expression

In above syntax,

  • We can use another if..else or any Scala expression in place of “expression”
  • Curly brackets can be omitted in if..else expression
Scala REPL Example: Finding Maximum number
scala> var (x,y,z) = (5,1,9)
x: Int = 5
y: Int = 1
z: Int = 9

scala> var var1 = if(x > y) x else y //Returns maximum of x and y (i.e. 5)
var1: Int = 5

scala> var var2 = if(x > y) if (x > z) x else z else if (y > z) y else z
var2: Int = 9
Scala REPL Example: Finding absolute number
scala> var a = -100
a: Int = -100

scala> var absVal = if(a < 0) -a else a
absVal: Int = 100

If else part in if..else expression is not specified than this expression will return “Any” as a return type.

scala> var a = 50
a: Int = 50

scala> val result = if(a%2 == 0) "even" //return type Any
result: Any = even

scala> val result = if(a%2 == 0) "even" else "odd" //return type java.lang.String
result: java.lang.String = even
References:

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>