This is the third part of the video series on Kotlin language. Read the first and second parts here. In this post, let’s take a look at the data types in Kotlin language.
Kotlin is a strongly typed language. In Java you have primitive and reference data types. ie., int type and a wrapper Integer class. But in Kotlin, all data types are Objects.
fun main(args:Array<String>){ var x:Int = 10 println(x) //x is an Int Object println(x.toString()) //On the JVM x is treated as primitive type int println(x.javaClass) //Prints int //On the JVM b is treated as primitive type boolean var b:Boolean = true println(b.javaClass) //Prints boolean }
As you can notice in the code above, x and b are declared as Int and Boolean types. Since they are reference types, we’re able to use the dot(.) notation on these variables. The .javaClass property returns the runtime Java class of this object.
Another cool feature of Kotlin, is Type Inference. Types can be omitted when you declare variables. Based on the value you assign, the compiler automatically infers the type of the variable.
var y = 20 println(y.javaClass)
In the code above, variable y is automatically inferred to be an integer. But how about type conversion. Say, you assign a number and then change it to String value. What happens?
var a = 20 println(a.javaClass) a = "now it's a string" //ERROR
In the code above, variable a is automatically inferred to be an integer based on the value assigned. But in the next line, when you assign a string value, the compiler throws an error, stating type mismatch.
You can find the video here.