Type system

In Kotlin, everything is an object. There are no primitive variables.

The following are the important numeric types:

  • Double--64 bit
  • Float--32 bit
  • Long--64 bit
  • Int--32 bit
  • Short--16 bit
  • Byte--8 bit

Unlike Java, Kotlin does not treat characters as a numeric type. Any numeric operation on a character will result in a compilation error. Consider the following code:

    var char = 'c'
//Operator '==' cannot be applied to 'Char' and 'Int'
//if(char==1) print (char);
Null safety

Java programmers are very familiar with java.lang.NullPointerException. Any operations performed on object variable referencing null will throw NullPointerException.

Kotlin's type system aims to eliminate NullPointerException. Normal variables cannot hold null. The following code snippet will not compile if uncommented:

    var string: String = "abc"
//string = null //Compilation Error

To be able to store null in a variable, a special declaration needs to be used. That is, type followed by a ?. For example, consider the following String? :

    var nullableString: String? = "abc"
nullableString = null

Once a variable is declared to be nullable, Only safe (?) or non-null asserted (!!.) calls are allowed. Direct references will result in compilation e

    //Compilation Error
//print(nullableString.length)
if (nullableString != null) {
print(nullableString.length)
}
print(nullableString?.length)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset