Scala Literals

In this tutorial, we will learn about the various types of literals in Scala with examples. By Shivang Yadav Last updated : April 02, 2023

What are Scala Literals?

In Scala, the literals are the set of values / symbols used for defining a constant in the code (Or, we can say that, a literal is a value that can be assigned to a variable. Literals are basic constants that are assigned to the variable.). There are many types of literals including the values, symbols, special characters.

Types of Scala Literals

A literal is a value that can be assigned to a variable. Literals are basic constants that are assigned to the variable.

  1. Integer Literals
  2. Float Literals
  3. Character Literals
  4. String Literals
  5. Boolean Literals

1) Integer Literals

Literals of type int or type Long. Integer literals can be declared using suffix L or I.


Decimal Literal: 
var i = 10L

Hexadecimal Literal: 
var I = 0xFFF

2) Float Literals

Literals of type float or type double. They use Suffix f/F for float and D/d for double.


Float Literal:
var i = 12.35f

Double Literal:
var I = 123.5445d

3) Character Literals

The character literals are the single characters written in single quotes ' '.


val char_value = 'T'
val arrow_code = '\u2191'

4) String Literals

The string literals are the sequence of characters written in double quotes " or triple double quotes """. There are two types of strings literals: Single-line and multi-line string literals. The single-line string literal is written in double quotes ", while multi-line string literals are written in triple double quotes """.


Single-line string literal:
val message = "Hello, world!"

Multi-line string literal:
"Include Help
is of the best 
Programming tutor"

5) Boolean Literals

A literal with any of two values, True/False.


val var1 = true
val var2 = false

Scala code to demonstrate the example of literals

object MyClass {
  def main(args: Array[String]): Unit = {
    // Integer Literals
    val x = 41
    val y = 0x1f // hexadecimal

    // Float Literal
    val pi = 31415e-4d

    // Boolean Literals
    val var1 = true
    val var2 = false

    // Character Literals
    val anyChar = 'X'
    val arrowUnicode = '\u2191'

    // String Literals
    var str1 = "Hello, world!"
    var str2 = """India,

    // printing the values
    println("x = " + x)
    println("y = " + y)
    println("var1 = " + var1)
    println("anyChar = " + anyChar)
    println("arrowUnicode = " + arrowUnicode)
    println("str1 = " + str1)
    println("str2 = " + str2)


x = 41
y = 31
var1 = true
anyChar = X
arrowUnicode = ↑
str1 = Hello, world!
str2 = India,

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.