fun main() { val name: String? = null val length = name?.length ?: -1 println(length) }
The variable name is nullable and set to null. The safe call operator ?. returns null for name?.length. The Elvis operator ?: then provides -1 as a default value. So, length becomes -1.
Kotlin's data classes automatically generate equals(), hashCode(), toString(), and copy methods, reducing the need to write repetitive code.
import kotlinx.coroutines.* fun main() { GlobalScope.launch { delay(1000L) println("World!") } println("Hello,") }
The main function launches a coroutine but does not wait for it. The program exits immediately, so "World!" is never printed.
listOf() creates an immutable (read-only) list. mutableListOf() and arrayListOf() create mutable lists. List(1, 2, 3) is invalid syntax.
describeShape with a Circle(5.0)?sealed class Shape class Circle(val radius: Double) : Shape() class Rectangle(val width: Double, val height: Double) : Shape() fun describeShape(shape: Shape): String = when(shape) { is Circle -> "Circle with radius ${shape.radius}" is Rectangle -> "Rectangle with width ${shape.width} and height ${shape.height}" } fun main() { println(describeShape(Circle(5.0))) }
The when expression covers all subclasses of Shape. Passing a Circle(5.0) matches the first case and prints the radius.
