In this topic we cover:
Both Kotlin and Java are object oriented languages though Kotlin also provides full support to functional programming. However, one major difference between Kotlin and Java is that everything in Kotlin is an object, unlike Java. Java has special primitive types that aren't objects. Thus don't natively support method calls, generics and cannot be assigned null. These include int,boolean etc.
To work with them as objects you have to use the wrapper objects from java.lang package like java.lang.Integer and java.lang.Boolean.
There is no need of this in Kotlin, those so called primitives are full objects in Kotlin. Sometimes, the Kotlin compiler maps those basic types to JVM primitives to boost performance.
The basic types in Kotlin include:
Kotlin has the following built-in number types:
| Type | Width |
| Byte ----- | 8 |
| Short ---- | 16 |
| Int ---------| 32 |
| Long ----- | 64 |
| Float ------| 32 |
| Double ---| 64 |
Literal constants for integral values in Kotlin comprise:
123. Longs are tagged by a capital L :
Note : Octal literals are not supported in Kotlin.
There is also a conventional notation for floating point numbers:
Example numbers declarations and initializations:
val int = 222 val long = 222545L val double = 25.68 val float = 25.68F val hexadecimal = 0xAB val binary = 0b01010101
Take note the following:
Kotlin allows you to use literals to make number constants more readable.
val oneMillion = 1_000_000 val creditCardNumber = 1234_5678_9012_3456L val socialSecurityNumber = 999_99_9999L val hexBytes = 0xFF_EC_DE_5E val bytes = 0b11010010_01101001_10010100_10010010
Unlike in java. There is no implicit widening of numbers in Kotlin. You convert numbers explicitly using predefined methods.
The methods include:
Examples of explicit casting of numbers in kotlin:
//Integer to long val num1 = 222 val long = num1.toLong() //Float to Double val num2 = 25.68 val double = num2.toDouble()