Variable initialization

In Scala, it's a good practice to initialize the variables once declared. However, it is to be noted that uninitialized variables aren't necessarily nulls (consider types like Int, Long, Double, Char, and so on), and initialized variables aren't necessarily non-null (for example, val s: String = null). The actual reasons are that:

  • In Scala, types are inferred from the assigned value. This means that a value must be assigned for the compiler to infer the type (how should the compiler consider this code: val a? Since a value isn't given, the compiler can't infer the type since it can't infer the type, it wouldn't know how to initialize it).
  • In Scala, most of the time, you'll use val. Since these are immutable, you wouldn't be able to declare them and then initialize them afterward.

Although, Scala language requires you to initialize your instance variable before using it, Scala does not provide a default value for your variable. Instead, you have to set up its value manually using the wildcard underscore, which acts like a default value, as follows:

var name:String = _

Instead of using the names, such as val1, val2 and so on, you can define your own names:

scala> val result = 6 * 5 + 8
result: Int = 38

You can use these names in subsequent expressions, as follows:

scala> 0.5 * result
res0: Double = 19.0
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.76.200