Scala - Literals



Values that can be assigned to the variables are known as literals. Literals are generally constant values. Literals are symbols we use to describe a constant value in our code. In Scala, there are various types of literals. For example, Character literals, String literals, Boolean literals, Integer and floating-point literals. The rules Scala uses for literals are simple and intuitive. This section explains all basic Scala Literals.

These are various types of literals in Scala.

Integer Literals

Integer literals are Integer values. Integer literals in Scala are usually of type Int. Integer literals can also be of type Long when a suffix 'L' or 'l' is added at the end. Both Int and Long are types of integer numerals.

The range of type Int is -2^31 to 2^30 and range of type Long is -2^63 to 2^62. Compiler will throw an error if the value of integer literal is outside the given range.

// Integer literal examples
val decimalNumber: Int = 42
val hexNumber: Int = 0x2A
val longDecimal: Long = 123L

Decimal literals have digits from 0 to 9. For example,

val count = 201

Hexadecimal literals have digits from 0 to 9 and A to F for value 11 to 15. These characters can be lowercase or uppercase. For example,

val count = 201

Hexadecimal literals have digits from 0 to 9 and A to F for value 11 to 15. These characters can be lowercase or uppercase. For example,

// The hexa-decimal number should be prefix
// with 0x or 0X.
val hexValue = 0xABCD

Octal literals have digits from 0 to 7. For example,

// The octal number should be prefix
// with 0o or 0O.
val y = 0o777

Binary literals can have either 0 or 1. For example,

// The binary number should be prefix
// with 0b or 0B.
val binaryNumber = 0b101010

Floating Point Literals are types of Float and Double. When you use F or f as a suffix at the end then it is float type. When you use D or d as a suffix at the end then it is Double type. For example,

// Double precision floating-point literal
val doubleValue: Double = 3.14

// Single precision floating-point literal
val floatValue: Float = 2.718f

Example

Scala program with various types of integers and floating-point literals:

// Creating object
object NumericLiteralsExample {
  
  // Main method
  def main(args: Array[String]) {

    // Decimal literals
    val decimalInt = 42
    val decimalLong = 123456789012345L
    val decimalDouble = 3.14
    val decimalFloat = 2.718f

    // Binary literals (prefix 0b or 0B)
    val binaryInt = 0b1101
    val binaryLong = 0B101010L

    // Octal literals (prefix 0o or 0O)
    val octalInt = 0o777
    val octalLong = 0O123456L

    // Hexadecimal literals (prefix 0x or 0X)
    val hexInt = 0x1A
    val hexLong = 0XABCDEF

  }
}

Character Literals

Character literals in Scala are Unicode characters that are printable. Character literals can also be represented using escape sequences. For example,

val y = 'z'
// Character literal in a single quote.

val z = '\u0066'
// Unicode representation of character literal.
// This Unicode represents f.

val newline = '\n'
// Escape sequence in character literals for a newline.

Example

Scala program of character literal:

// Creating object
object CharLiteralExample {

	// Main method
	def main(args: Array[String]) {

		// Creating a character literal
		// in single quote
		val a = 'c'

		// Unicode representation of
		// character literal
		val b = '\u0041'

		// Escape sequence in character
		// literals
		val c = '\t'

	}
}

Note that single quotes are used to enclose character literals.

String Literals

String literals in Scala are sequences of characters. Double quotes are used to enclose String literals and can be managed by String Interpolation. For example,

val name = "Tutorialspoint"

Scala program of literals:

// Creating object
object literal
{

	// Main method
	def main(args: Array[String])
	{
		// Creating a string 
		// literal
		val name = "Tutorialspoint"

		// Displays string 
		// literals
		println(x)
	}
}

Note that quotation marks are used for single-line strings.

Multi-line String Literals

Multiline string literals have multiple lines of characters. For example,

val name = """Tutorialspoint"""

Example

Scala program of multi-line string literals:

// Creating object
object MultiLineStringLiteralExample {

	// Main method
	def main(args: Array[String]) {
		// Creating a multiple
		// line string literal
		val poem =
			"""The road not taken,
			by Robert Frost,
			Two roads diverged in a wood"""

		// Displays multiple
		// lines
		println(poem)
	}
}

Note that triple quotes are used for multi-line strings.

Boolean Literals

Boolean literals have either true or false value. For example,

val correct = true

Example

Scala program of Boolean literals:

// Creating object
object BooleanLiteralExample {

	// Main method
	def main(args: Array[String]) {

		// Assigning true
		val isSunny = true

		// Assigning false
		val isRainy = false

		// Displays results
		println(isSunny)
		println(isRainy)
	}
}

Symbol Literals

In Scala, the symbol is a case class and is represented as a shorthand for the expression `scala.Symbol("x")`. For example,

package scala

final case class MySymbol private (name: String) {
  override def toString: String = "'" + name
}

Null Values

The null value in Scala is compatible with every reference type because its type is `scala.Null`.

Escape Sequences

In Scala, escape sequences are used for character and string literals for various purposes. These are some of them:

\b represents backspace (BS).
\t represents horizontal tab (HT).
\n represents form feed (FF).
\f also represents form feed (FF).
\r represents carriage return (CR).
\" represents a double quote (").
\' represents a single quote (').
\\ represents a backslash ().

For example,

object HelloWorld {
  def main(args: Array[String]): Unit = {
    println("Hello World, This is Scala simple program\nwith a new line.")
  }
}

The output of the above code will be:

Hello World, This is Scala simple program
with a new line.
Advertisements