Variables and constants

You declare a variable using the var keyword, and declare constants with the val keyword. When declaring a variable or constant, its type doesn't have to be explicitly defined. The type will be inferred from context. A val can only be initialized once. A variable or constant can only be assigned a null value if it's explicitly declared as a nullable type. You declare a nullable type by appending a ? to the end of the type:

var a: String = "Hello"
var b = "Hello"

val c = "Constant"
var d: String? = null // nullable String

b = null // will not compile

b = 0 // will not compile
c = "changed" // will not compile

For instance, in the preceeding code, a and b will both be treated as String. When trying to reassign a variable with an inferred type, a value of a different type will throw an error. A val can only be initialized once. 

..................Content has been hidden....................

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