Pt2 – Introduction to variables in Scala

Of vals and vars
In this 2nd video I introduce variables or, to be precise, constants. The notion of final variables in Scala is even more pronounced than in Java. A final variable is declared as a val and a non-final variable is declared as a var. The var type is rarely used and increasing use of val is a good sign of moving from creating Java-style code to fully embracing the functional side of Scala.

Here is the class I use in my video (I explained the package declaration and extends App in the first video):

package com.vff

object Video2 extends App {

  val age:Int = 42
  
  val ageLimit = 40
  
  val isTooOld = (age > ageLimit)
  
  if (isTooOld) {
    println("Sorry - too old!")
  } else {
    println("You're young enough")
  }
  
}

Here we have some vals being declared – both achieve the same result but in different ways.

  val age:Int = 42

Here we are declaring the field age is a val, and therefore final, it is an Int – remember no primitive types in Scala – and its value is 42. No need for a semi-colon unless we put another statement on this line.

The next declaration demonstrates Scala understanding what type to assign when creating an Int(eger) value:

  val ageLimit = 40 

We didn’t need the ‘:Int’ here – it is understood. We could force the type as we did when declaring age but there is no need.

  val isTooOld = (age > ageLimit)

Again, we declare a final Boolean field isTooOld and assign its value. As with a final Java field any attempt to reassign would be a compiler error.

So, here is the video, I hope you enjoy and will appreciate any feedback:

Back to Part 1

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s