Den Dribbles

Scala Data Types

June 18, 2019

The presumes you have Scala installed on the local system.

This is just the basics on declaring variables in Scala and what data types are available.

Declaring Variables

Create file src/main/scala/Playground.scala with the following.

object Playground extends App {
  val x: Int = 42
  println(x)
}
  • println will allow us to print to the console.
  • Extending App allows us to run the file in the command line correctly.
  • val are immutable - this is the Scala and functional programming way.

Say we remove the explicit type:

object Playground extends App {
  val x = 42
  println(x)
}

This still works as the compiler infers the type to be an Int.

Declaring various types

Below we will run through a declaration of each type.

object Playground extends App {
  val x: Int = 42
  val y: String = "Hello, Friend!"
  val z: Boolean = true
  val a: Char = 'a' // Note single quotes
  val b: Short = 1234
  val c: Long = 1234123412341234L // Note the L - similar to Java longs
  val d: Float = 2.0f // Note the f - similar to Java
  val e: Double = 2.14 // No marker needed

  /* in order to mutate a variable */
  var f: Int = 1
  f = 2 // this is known as a side effect
}

Note that the val and var keywords have different meanings. val is a constant and follows functional, immutable conventions while var is mutable and changing a mutable variable is known as a side effect.


A personal blog on all things of interest. Written by Dennis O'Keeffe, Follow me on Twitter