Outdated Notice
As we showed in the previous lesson, when you create a new variable in Scala you can explicitly declare its type, like this:
val count: Int = 1
val name: String = "Alvin"
However, you can generally leave the type off and Scala can infer it for you:
val count = 1
val name = "Alvin"
In most cases your code is easier to read when you leave the type off, so this inferred form is preferred.
The explicit form feels verbose
For instance, in this example it’s obvious that the data type is Person
, so there’s no need to declare the type on the left side of the expression:
val p = new Person("Candy")
By contrast, when you put the type next to the variable name, the code feels unnecessarily verbose:
val p: Person = new Person("Leo")
In summary:
val p = new Person("Candy") // preferred
val p: Person = new Person("Candy") // unnecessarily verbose
Use the explicit form when you need to be clear
One place where you’ll want to show the data type is when you want to be clear about what you’re creating. That is, if you don’t explicitly declare the data type, the compiler may make a wrong assumption about what you want to create. Some examples of this are when you want to create numbers with specific data types. We show this in the next lesson.
Contributors to this page:
Contents
- Introduction
- Prelude꞉ A Taste of Scala
- Preliminaries
- Scala Features
- Hello, World
- Hello, World - Version 2
- The Scala REPL
- Two Types of Variables
- The Type is Optional
- A Few Built-In Types
- Two Notes About Strings
- Command-Line I/O
- Control Structures
- The if/then/else Construct
- for Loops
- for Expressions
- match Expressions
- try/catch/finally Expressions
- Scala Classes
- Auxiliary Class Constructors
- Supplying Default Values for Constructor Parameters
- A First Look at Scala Methods
- Enumerations (and a Complete Pizza Class)
- Scala Traits and Abstract Classes
- Using Scala Traits as Interfaces
- Using Scala Traits Like Abstract Classes
- Abstract Classes
- Scala Collections
- The ArrayBuffer Class
- The List Class
- The Vector Class
- The Map Class
- The Set Class
- Anonymous Functions
- Common Sequence Methods
- Common Map Methods
- A Few Miscellaneous Items
- Tuples
- An OOP Example
- sbt and ScalaTest
- The most used scala build tool (sbt)
- Using ScalaTest with sbt
- Writing BDD Style Tests with ScalaTest and sbt
- Functional Programming
- Pure Functions
- Passing Functions Around
- No Null Values
- Companion Objects
- Case Classes
- Case Objects
- Functional Error Handling in Scala
- Concurrency
- Scala Futures
- Where To Go Next