Data types
Integer types
Some points regarding variables and data types in Kotlin:
Kotlin variable declaration
greeting = "Hi again" // not allowed, 'greeting' immutable due to 'val' declaration
greeting = "Hello World, v2" // allowed, 'var' declaration allows mutability var age = 21 // mutable variable (value and reference to object can change) var age: Int = 21 // no semi-colon required at end of declaration statement val name = "John" // 'val' for immutable variables (reference to object unchangable ) val name: String = "John" // equivalent to declaration above val isHuman: Boolean = true Kotlin and immutability or null safety val str: String = null // not allowed val str: String? = null // use '?' after the data type when wanting to assign 'null' val i: Int? = null - Kotlin will warn at compile time when a variable is null Unsafe and safe operators for null in Kotlin // 'str' is null str!!.length // using unsafe operator '!!', throws null pointer exception str?.length /** safe operator that returns null if 'str' is null, the value of 'str.length' if 'str' is not null **/ val length = str?.length ?: -1 /** ?: - Elvis operator. If 'str' is null, assign -1 to 'length', otherwise, length of 'str' assigned value of its 'length' **/ Comments are closed.
|
AuthorExploring Android and mobile web design, security, and development. Archives
March 2021
Categories |