Reading Time: 2 minutesKotlin constants are fixed values that does not change during program execution.
These fixed values are called literals.
Kotlin constatns can be of any basic data types.
- Integer constants
- Floating point constants
- Character constants
- String literals etc.
Kotlin supports the following literals for integral values.
- Decimals: 123, 34567, 22222
- If you want to represent number of long data type
- You can do so by using L tag
- Long type: 123L, 34567L, 22222L
- Hexadecimals: 0x0F, 0x0A, 0x0C, 0x0b
- It contains hexadecimals values
- They are made up for 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.
- Binaries: 0b0001100, 0b000101, 0b001101, 0b101
- It contains binary number
- They are made up of 0 and 1 only
- Write 0b to tell the compiler that it is binary number
You can use underscores to make number constants more readable.
As floating-point numbers are by default interpreted as Double, Floats are tagged by f or F.
Floating Point Literals / Constants
A floating point literals contain integer part, decimal part, a fractional part and exponent part.
You can represent point in 2 ways.
To represent floating-point Kotlin constants in this form, there should be at-least one digit after decimal point
Character Literals / Constants
In Kotlin, characters are represented by the type Char.
Single quotes ” are used to denote a charater variable.
‘a’, ‘b’, ‘1’, ‘2’, ‘c’, ‘g’
Special characters can be escaped using a backslash.
\t, \b, \n, \
String Literals / Constants
Kotlin has 2 types of string literals.
It can have escaped characters in them
Raw Strings can have newlines and arbitrary tests in them.
It is delimited by using triple quotes (“””)
It contains no escaping.