// Throws Index out of bound Error // nullableString?.get(0) ?: throw IndexOutOfBoundsException()
// prints "The value is string" nonNullableString?.let { value -> print("The value is ${value}") } // does not print nullableString?.let { value -> print("The value is ${value}") }
// value-parameter can be omitted nullableString?.let { print("The value is ${it}") } }
8. Class
class Person(var name: String, var age: Int) { lateinit var hobby: String // recommended to use private
init { print("Printed this when a class is instantiated") }
fun createPerson() { var person = Person("chris", 20) print(person.age) // print(person.hobby) // Not Initialized error occur
var person2 = Person("chris", 20, "debugging") print(person2.age) print(person2.hobby) person2.nextYear()
9. Lambda
fun lambdaExample() { var result: (name: String, age: Int) -> (String) = { name, age -> "My name is ${name}, and I'm ${age} years old" }
// Inference type var result2 = { name: String, age: Int -> "My name is ${name}, and I'm ${age} years old" }
var printPretty: String.() -> String = { "My name is ${this}" } "chris".printPretty() // returns "My name is chris"
var printPretty2: String.(age: Int) -> String = { "My name is ${this}, and I'm ${it} years old" } "chris".printPretty2(20) // returns "My name is chris, and I'm 20 years old"
var printPretty3: String.(age: Int, hobby: String) -> String = { age, hobby -> "My name is ${this}, and I'm ${age} years old, and hobby is ${hobby}" } "chris".printPretty3(20, "debugging") // returns "My name is chris, and I'm 20 years old, and hobby is debugging"
fun invokeLambda(lambda: (Int) -> Boolean): Boolean { return lambda(1) }
fun dataClassExample() { data class PersonData( var name: String, var age: Int )
var person = PersonData("chris", 20) person.toString() // returns "PersonData(name=chris, age=20)" person.age++ person.name = "Anonymous" }
11. Companion object
class PersonCompanion(var name: String, var age: Int) { companion object { private const val MAX_AGE = 120 fun create( name: String, age: Int = MAX_AGE ): Person { return Person(name, age) } } }
fun companionExample() { var person = PersonCompanion.Companion.create("chris", 20) var person2 = PersonCompanion.create("chris", 20) var person3 = PersonCompanion.create("chris") person3.age // returns 120 }
12. Object
data class Ticket(val price: Int)
object TicketFactory { val tickets = arrayListOf<Ticket>() fun addTicket(price: Int) { tickets.add(Ticket(price)) } }