Thursday 20 October 2016

Basics of Scala : Defining a Value in Scala : Day 2 Learnings

Values are immutable, typed storage units, and by convention are the default method for storing data. You can define a new value using the val keyword.

Syntax: Defining a Value

  1. val <identifier>[: <type>] = <data>


Values require both a name and assigned data, but they do not require an explicit type. If the type is not specified (i.e., the “: <type>” syntax is not included), the Scala compiler will infer the type based on the assigned data.

Here are some examples of defining values with their type in the Scala REPL:

  1. scala> val x: Int = 20
  2. x: Int = 20
  3. scala> val greeting: String = "Hello, World"
  4. greeting: String = Hello, World
  5. scala> val atSymbol: Char = '@'
  6. atSymbol: Char = @


You may have noticed from the syntax diagram that specifying the type in value definitions is optional. In situations where it is possible to deduce the type of the value based on its assignment (for example, the literal 20 in the first example is obviously an integer), you can leave off the type from a value definition. The Scala compiler will then discern the type of the value from its assignment, a process known as type inference. Values defined without a type are not typeless; they are assigned the proper type just as if the type had been included in the definition.

Let’s try the examples again without specifying their types:

  1. scala> val x = 20
  2. x: Int = 20
  3. scala> val greeting = "Hello, World"
  4. greeting: String = Hello, World
  5. scala> val atSymbol = '@'
  6. atSymbol: Char = @


In this example the values end up having the same types ( Int , String , and Char ) as they did when the types were explicitly stated. The Scala compiler, via the REPL, was able to deduce that the literal 20 corresponds to the type Int , the literal "Hello, World" to the type String , and the literal @ to the type Char .

Using Scala’s type inference is a helpful shortcut when writing code because it removes the need to explicitly write the type of a value. As a guideline it should only be used when it does not reduce the readability of your code. In the case that someone reading your code would not be able to figure out what the type of the value is, it would be better to include the explicit type in the value definition.

Although type inference will deduce the correct type to use to store data, it will not override an explicit type that you set. If you define a value with a type that is incompatible with the initial value you will get a compilation error:

  1. scala> val x: Int = "Hello"
  2. <console>:7: error: type mismatch;
  3. found: String("Hello")
  4. required: Int
  5. val x: Int = "Hello"


The error here affirms that an Int type cannot be used to store a String .



Share this article with your friends.

No comments :

Post a Comment

Related Posts Plugin for WordPress, Blogger...