Scala, a powerful and expressive programming language, offers a rich set of data types. Understanding these types is crucial for writing efficient and type-safe Scala code.
Scala provides several numeric types to handle different ranges of values:
val myByte: Byte = 100
val myShort: Short = 30000
val myInt: Int = 2000000000
val myLong: Long = 9000000000L
val myFloat: Float = 3.14f
val myDouble: Double = 3.14159265359
The Boolean type represents logical values and can be either true or false.
val isScalaFun: Boolean = true
val isCodingBoring: Boolean = false
Char represents a single 16-bit Unicode character.
val myChar: Char = 'A'
val unicodeChar: Char = '\u0041' // Unicode for 'A'
String represents a sequence of characters. In Scala, strings are immutable.
val greeting: String = "Hello, Scala!"
val multiLine: String = """
This is a
multi-line
string
"""
Unit is Scala's equivalent to Java's void. It's used when a function doesn't return a meaningful value.
def printHello(): Unit = {
println("Hello")
}
Scala features powerful type inference, allowing you to omit type annotations in many cases. The compiler can often deduce the type based on the context.
val inferredInt = 42 // Compiler infers Int
val inferredDouble = 3.14 // Compiler infers Double
val inferredBoolean = true // Compiler infers Boolean
Understanding Scala's data types is fundamental to writing robust and efficient code. As you progress, you'll encounter more complex types like Option, Either, and various collection types, which build upon these basic types to provide powerful abstractions.