Right now, let's see how we define the most common types in Scala such as Int
, Double
, Boolean
, and String
. Remember, you can create these variables using val
or var
depending on your needs.
We will see Scala variable type in Scala REPL as follows:
$ scala Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77). Type in expressions for evaluation. Or try :help. scala> val x = 10 x: Int = 10 scala> val y = 11.1 y: Double = 11.1 scala> val b = true b: Boolean = true scala> val f = false f: Boolean = false scala> val s = "A Simple String" s: String = A Simple String scala>
For the variables in the preceding code, we did not define the type. Scala language figures it out for us. However, it is possible to specify the type if you want. In Scala, the type comes after the name of the variable.
We will see Scala variables with explicit typing at Scala REPL as follows:
$ scala Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77). Type in expressions for evaluation. Or try :help. scala> val x:Int = 10 x: Int = 10 scala> val y:Double = 11.1 y: Double = 11.1 scala> val s:String = "My String " s: String = "My String " scala> val b:Boolean = true b: Boolean = true scala>