What are data types in Scala?

We use data types to define what type of value a variable holds. For example, if we want to declare a variable and assign a number to it, we use the integer, int, data type.

Similarly, if we want a variable to store textual data, we use the string data type, which is a collection of characters.

There are several other data types, each of which has its own size.

Scala data types

In Scala, we have various data types similar to what we use in Java or C++. Those data types are:

  • Integer: This data type holds a numeric value of a maximum of 32-bits. The integer data type has two subtypes:

    • long: holds a numeric value of maximum 64-bits.

    • short: holds a numeric value of maximum 16-bits.

  • String: This data type supports textual data, written inside ("") double-quotes.

  • Boolean: We use the boolean data type in a situation where we want to declare variables that have true or false values.

  • Char: It is short for character. char only supports a single character written inside ('') single-quotes.

  • Float: Also known as floating-point, this data type is used to store real numbers, that include a fractional part, in a variable that has a capacity of 32-bits.

  • Double: This data type is similar to Float. It just holds a max length of 64-bits.

Data types in Scala

Code

Let’s observe the following example to see how these data types can be implemented in Scala.

// var keyword is used to
// declare variables in Scala
var int: Int = 50
var short: Short = 40
var long: Long = 80
var string: String = "Hello World!"
var bool: Boolean = true
var char: Char = 'H'
var float: Float = 3.142f
var double: Double = 3.141592653589793
println("1. integer: " + int)
println("2. short: " + short)
println("3. long: " + long)
println("4. string: " + string)
if (bool == true) {
println("5. boolean: this is a true value!")
}
println("6. char: " + char)
println("7. float: " + float)
println("8. double: " + double)

Explanation

var keyword is used to declare variables. To initialize those variables, we write their data types followed by the value we want to store.

println() is used to display the values of each variable.

Copyright ©2024 Educative, Inc. All rights reserved