Back to home

Declaring VariablesDeclaring various types
Scala Data Types main image

Scala Data Types

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.

1 2 3 4 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:

1 2 3 4 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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 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.

Dennis O'Keeffe

  • Melbourne, Australia

Hi, I am a professional Software Engineer. Formerly of Culture Amp, UsabilityHub, Present Company and NightGuru.
I am currently working on, Den Dribbles and LandPad .

Related articles


Get fresh posts + news direct to your inbox.

No spam. We only send you relevant content.