🎉 I'm releasing 12 products in 12 months! If you love product, checkout my new blog workingoutloud.dev

Back to home

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.

    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.

    Personal image

    Dennis O'Keeffe

    @dennisokeeffe92
    • Melbourne, Australia

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

    1,200+ PEOPLE ALREADY JOINED ❤️️

    Get fresh posts + news direct to your inbox.

    No spam. We only send you relevant content.

    Scala Data Types

    Introduction

    Share this post