Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Expressions and Statements in Scala

Tags:

scala

I'm new in Scala world and want to know what is the difference between Expressions and Statements and Why if-else is used for expression, not statements. And if there is a way to use statement in if-else?

like image 203
slavov Avatar asked Jan 23 '16 11:01

slavov


Video Answer


1 Answers

Everything in Scala is an Expression!

Theory:

  • Instructions/Statements are executed in imperative languages like Java but Expressions are evaluated in Functional languages(Declarative programming) like Scala.
  • Instruction means Do something for me but Expression means give me the Value of something.

Practical:

If else expression:

val aCondition = true
val aConditionValue = if(aCondition) 4 else 2
println(aConditionValue) 

To prove this we can just use this Expression in println directly

println(if(aCondition) 4 else 2)

Note: Here If else expression is giving the value instead of setting/doing something based on condition.

like image 142
Keshav Lodhi Avatar answered Oct 06 '22 00:10

Keshav Lodhi