Kotlin Constants And Literals

Kotlin constants are fixed values that does not change during program execution. These fixed values are called literals. Kotlin Constants can be of any basic data types. For example, Integer constants, Floating point constants, Character constants, String literals etc. Like other languages, you must assign some value to the constant while declaring it because you can not change it later on.

Integer Constants In Kotlin

Like Other programming languages, integer constant in kotlin contains fixed integer value. In Kotlin, there are following kinds of Literal constants for integral values –
a. Decimal
b. Hexadecimal
c. Binaries

a. Decimal

This represents any integer value. For example,

 123, 140, 122222, 43454, 6546 etc.

Like other programming languages, if you want to represent number of long data type, you can do so by using L tag. For example,

123L, 167L, 43465L etc.

b. Hexadecimal

– It contains hexadecimal values.
– They are made up of letters from 0-9 and A-E (or a-e).
– You need to write 0x before number to tell the compiler that it is hexadecimal number.
– Example,

0x0F, 0x0A, 0x0C, 0x0b etc.

c. Binaries

– It contains binary number.
– They are made up of 0 and 1 only.
– You need to write 0b to tell the compiler that it is binary number.
– Example,

0b000110, 0b000101,  0b001101,  0b101 etc.
UnderScore in Numeric literals

You can use underscore in numeric kotlin constants to make it more readable. For example,

var count = 100_100_000 
var lCount = 100_100_000L
var fCount = 100_100_000F
val creditCardNumber = 1234_8989_9012_3456L
val socialSecurityNumber = 999_99_89898L
val hexBytes = 0xEE_EC_EE_5E
val bytes = 0b11010010_01101001_00111_10010010

Note that characters are not numbers in kotlin.

Some Valid Integer Kotlin Constants –
12, 15, 16, 899, 434, 455, 134L, 656L,  65654L,  0xAB, 0xAC, 0b101, 0b10111 etc.
Some Invalid Integer Kotlin Constants –
0xAGH, 0b8989, 0b687, 0xTRH etc. 
Did you know?
Octal literals are not supported in Kotlin.

– Exercise

1. What is output?

fun main (args  : Array<String>) {
    var cost = 10
    println("cost = $cost");

    var numb = 10000L
    println("numb = $numb")

    var count = 0x0C
    println("count = $count")

    var value = 0b10
    println("value = $value")
}

2. What is output?

fun main (args  : Array<String>) {
    var cost = 100_100_100
    println("cost = $cost");

    var numb = 1000_10000L
    println("numb = $numb")

    var count = 0x0C_0c_0f
    println("count = $count")

    var value = 0b10_1000_10
    println("value = $value")
}

Floating Point Literals / Constants in Kotlin

A floating point literals contain integer part, decimal part, a fractional part and exponent part. You can represent floating point in 2 ways.
a. Decimal form : To represent floating point kotlin constants in this form, there should be at-least one digit after decimal point. For example, 12.43, 123.54F, 54.5 etc.
b. Exponential form : You can represent kotlin constants, in this form, as below –
      123e-5, 123.4e1F, 12.1e2 etc.

Kotlin also supports a conventional notation for floating-point numbers.

Doubles by default: If you are using any floating point number without any tag, it would be interpreted as Double. For example,

123.23, 154.3e8, 134.98 etc.

Floats are tagged by f or F: If you want to use single-precision floating point number, then, you need to use f or F tag. For example,

123.4f, 123.4F, 125.7F, 54.2e6F, 76.3e-8F etc.
1. What is output?

fun main (args  : Array<String>) {
    var cost = 10.59
    println("cost = $cost");

    var numb = 10.5F
    println("numb = $numb")

    var count = 2.3e2
    println("count = $count")

    var value = 1.2e-2
    println("value = $value")
}



Character Literals / Constants in Kotlin

In Kotlin, characters are represented by the type Char. For example,

var letter: Char
letter = 'm'
println("$letter")

Note: Here, letter is variable of Char type.

– Single quotes ‘ ‘ are used to denote a character variable. For example,

'a', 'b', '1', '2', 'c', 'g' etc.

– Special characters can be escaped using a backslash. For example,

\t, \b, \n, \r	etc.

– You need to use the unicode escape sequence syntax to encode any other character. For example, ‘\uFF00’.

1. What is output?

fun main (args  : Array<String>) {
    var gender = 'F'
    println("gender = $gender");
}

String Literals / Constants in Kotlin

Kotlin has two types of string literals.
a. Escaped Strings.
b. Raw Strings.

a. Escaped Strings

– It can have escaped characters in them. For example,

val s = "Hello, world!\n"

Note: It is same as String type in Java. Like conventional way, Escaping is done using backslash.

b. Raw Strings

– Raw Strings can have newlines and arbitrary texts in them. It is delimited by using triple quotes (“””). It contains no escaping. For example,

val text = """
	This is
	Rajeev Kumar
"""

– String may contain template expressions. Template expressions is piece of code whose values are evaluated and concatenated with the string. It starts with $ sign and contains either a simple name or an arbitrary expression in curly braces. For example,

Simple Name

val x = 324
val z = "x = $x" // evaluates to "x = 324"
val name = "Rahul Kumar"
val text = "Your name is = $name" // evaluates to "Your name is = Rahul Kumar"



Arbitrary expression

val s = "abc"
val str = "$s.length is ${s.length}" // evaluates to "abc.length is 3"

– You can use template in both types of strings. If you need to represent a literal $ character in a raw string (which doesn’t support backslash escaping), you can use the following syntax:

val price = """
${'$'}4.564
"""
Below are some programs related to kotlin constants. Are you able to answer them? If Not, please go through this post one more time.
1. What is output?

fun main (args  : Array<String>) {
    var name = "Rahul Kumar"
    println("name = $name");

    var intro = """ I live in Delhi """
    println("intro = $intro")
}

2. What is output?

fun main (args  : Array<String>) {
    var message = "Hello World \n"
    println("message = $message");

    var intro = """ Hello World \n"""
    println("intro = $intro")
}

3. What is output?

fun main (args  : Array<String>) {
    val s = "abcd"
    val str = "$s.length is ${s.length}"
    println(str)
}

4. What is output?

fun main (args  : Array<String>) {
    val price = """
    ${'$'}4.564
    """
    println(price)
}




Using const Keyword to Define Constant in Kotlin

const are compile time constant in kotlin. compile time constants need to fulfil following requirements –
a. Top-level or member of an object.
b. Initialised with a value of type String or primitive type.
c. No custom getter.

It means their value has to be assigned during compile time, unlike val where it can be done at runtime. It means this type of kotlin constant can never be assigned to a function or any class constructor.

You can define kotlin constants using const keyword if you need. You can define it as below.

const val amount = 1000

Here, amount is variable whose value is 1000 and it can not be changed. It’s fixed during program execution.

– A complete example

1. What is output?

fun main (args  : Array<String>) {
	const var count = 1000
	println("$count");
}

2. What is output?

fun main (args  : Array<String>) {
	const val count = 1000
	println("$count");
}

3. Below is an example in android written using kotlin language. Can you guess what is output of the program?

package com.tutorialwing.kotlinbasictypes

import android.os.Bundle
import android.support.v7.app.AppCompatActivity

const val count = 1000

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        println("$count");
    }
}

Conclusion

In this tutorial, we discussed about kotlin constants and literals. we also went through different examples corresponding to each data type. You can check about Kotlin programming language to know more.

Leave a Reply