var - Mutable (For variables that change) //Variable type is inferred from the context val name = "John" name = 2 //Error, because name type is String //Explicit type var list : List<String> = ArrayList()
name: String, val age: Int) class Person(var name: String, var age: Int) class Person private constructor(name: String, age: Int) annotation class Inject class Person @Inject constructor(val name: String, val age: Int) Class Declarations
{ val person = Person("John Doe", 30) //Assigning null person.age = null //Error } //Makes it a Nullable type class Person(val name: String, var age: Int?) Nullability
val nextAge = person.age!! + 1 //Use Elvis Operator val nextAge = (person.age ?: 0) + 1 //Error val nextAge = person.age + 1 //We can use safe call operator to safely call methods on potentially nullable variables savedInstanceState?.doSomething()
String { return "$name is $age years old" } override fun equals(other: Any?): Boolean { return (other is Person && other.name == name) } } Equality and String interpolation
Int) • Along with this you get - • equals/hashcode • toString() like Person(name=John Doe, age=42) • Destructuring declarations - componentN() • Copy with modified attributes - copy()
Array<String>) { val person = Person("John Doe", 42) val (name, age) = person } Destructuring Declaration Copy() val person2 = person.copy("Johnny Depp", 54) println(person2)
Hadi Hariri • Learning Kotlin Series on Fragmented Podcast • From Java to Kotlin • Antonio Leiva’s blog • Android development with Kotlin - Jake Wharton • Kotlinize your Android Development - Akshay Chordiya References