### Constructor delegation examples Source: https://kotlinlang.org/spec/kotlin-spec.html Illustrates constructor delegation rules: classes without a primary constructor can delegate to super or another secondary constructor; classes with a primary constructor must delegate to primary or secondary via this(...). Includes commented-out error and valid delegation examples. ```kotlin open class Base class POKO : Base() {} class NotQuitePOKO : Base { constructor() : super() {} } class Primary(val s: String) : Base() { constructor(i: Int) : this(i.toString()) {} constructor(d: Double) : this(d.toInt()) {} // Error, has primary ctor, // needs to delegate to primary or secondary ctor // constructor() : super() {} } class Secondary : Base { constructor(i: Int) : super() {} constructor(s: String) : this(s.toInt()) {} // Ok, no primary ctor, // can delegate to `super(...)` constructor() : super() {} } ``` -------------------------------- ### Type capturing example with bounded type parameter Source: https://kotlinlang.org/spec/kotlin-spec.html Illustrates type capturing with a bounded type parameter and contravariant type argument. The example defines invariant, covariant, and contravariant interfaces, then uses a bounded interface to show how a contravariant argument leads to a captured type with bounds B <: KB <: A, enabling the assignment to Root. ```kotlin interface Inv interface Out interface In interface Root interface A interface B : A interface C : B fun mk(): T = TODO() interface Bounded : Root fun test01() { val bounded: Bounded = mk() // Bounded <: Bounded where B <: KB <: A // (from type capturing) // Bounded <: Root // (from supertype relation) val test: Root = bounded ``` -------------------------------- ### Enum class example with implicit members and overrides Source: https://kotlinlang.org/spec/kotlin-spec.html This example shows a simple enum class State with three entries and demonstrates the implicit members: name, ordinal, comparison, toString, valueOf, and values. It also shows an enum class Direction with additional declarations and overridden properties in its entries. ```kotlin enum class State { LIQUID, SOLID, GAS } ... State.SOLID.name // "SOLID" State.SOLID.ordinal // 1 State.GAS > State.LIQUID // true State.SOLID.toString() // "SOLID" State.valueOf("SOLID") // State.SOLID State.valueOf("Foo") // throws exception State.values() // arrayOf(State.LIQUID, State.SOLID, State.GAS) ... // enum class can have additional declarations that may be overridden in its values: enum class Direction(val symbol: Char) { UP('^') { override val opposite: Direction get() = DOWN }, DOWN('v') { override val opposite: Direction get() = UP }, LEFT('<') { override val opposite: Direction get() = RIGHT }, RIGHT('>') { override val opposite: Direction get() = LEFT }; abstract val opposite: Direction } ``` -------------------------------- ### Call handleConfig with a mutable map Source: https://kotlinlang.org/spec/kotlin-spec.html Calls handleConfig with a mutable map containing the keys "parent" and "host". This is the main entry point for the example that demonstrates property delegation with a map. ```kotlin fun main() { handleConfig(mutableMapOf( "parent" to "", "host" to "https://kotlinlang.org/" )) } ``` -------------------------------- ### Kotlin class initialization order example Source: https://kotlinlang.org/spec/kotlin-spec.html Illustrates the initialization order for a Kotlin class with a primary constructor, a secondary constructor, interface delegation, and init blocks. The commented output shows the order of initialization and how uninitialized properties can leak undefined values. ```kotlin open class Base(val v: Any?) { init { println("2: $this") } } interface I class Init(val a: Number) : Base(0xC0FFEE) /* (2) */, I by object : I { init { println("2.5") } } /* (2.5) */ { init { println("3: $this") /* (3) */ } constructor(v: Int) : this(v as Number) { println("10: $this") /* (10) */ } val b: String = a.toString() /* (4) */ init { println("5: $this") /* (5) */ } var c: Any? = "b is $b" /* (6) */ init { println("7: $this") /* (7) */ } val d: Double = 42.0 /* (8) */ init { println("9: $this") /* (9) */ } override fun toString(): String { return "Init(a=$a, b='$b', c=$c, d=$d)" } } fun main() { Init(5) // 2: Init(a=null, b='null', c=null, d=0.0) // 3: Init(a=5, b='null', c=null, d=0.0) // 5: Init(a=5, b='5', c=null, d=0.0) // 7: Init(a=5, b='5', c=b is 5, d=0.0) // 9: Init(a=5, b='5', c=b is 5, d=42.0) // 10: Init(a=5, b='5', c=b is 5, d=42.0) // Here we can see how the undefined values for // uninitialized properties may leak outside } ``` -------------------------------- ### String interpolation example with $ and ${} Source: https://kotlinlang.org/spec/kotlin-spec.html Shows a line string and a multiline string using both interpolation forms. The multiline string allows newlines but does not support escaping the $ symbol. ```kotlin val a = "Hello, $x is ${foo()}" val b = """ Hello, $x is "${foo()}" """ ``` -------------------------------- ### Simple class declaration examples Source: https://kotlinlang.org/spec/kotlin-spec.html Illustrates simple class declarations: a base class without supertypes, a class with a primary constructor property, a class with an init block, a class with a secondary constructor delegating to the supertype, and a class with a companion object. The comments explain each part. ```kotlin // An open class with no supertypes // open class Base // A class inherited from `Base` // // Has a single read-only property `i` // declared in its primary constructor // class B(val i: Int) : Base() // An open class with no superclasses // // Has a single read-only property `i` // declared in its body // // Initial value for the property is calculated // in the init block // open class C(arg: Int) { val i: Int init { i = arg * arg } } // A class inherited from `C` // Does not have a primary constructor, // thus does not need to invoke the supertype constructor // // The secondary constructor delegates to the supertype constructor class D : C { constructor(s: String) : super(s.toInt()) } // An open class inherited from `Base` // // Has a companion object with a mutable property `name` class E : Base() { companion object /* Companion */ { var name = "I am a companion object of E!" } } ``` -------------------------------- ### Initialized variable analysis with run contract Source: https://kotlinlang.org/spec/kotlin-spec.html Example showing that the `run` contract allows assignment to a read-only variable inside its lambda, avoiding an initialization error. ```kotlin val x: Int run { // run invokes its argument exactly once x = 4 } // could be error: x is not initialized // but is ok println(x) ``` -------------------------------- ### Kotlin example for killDataFlow inference Source: https://kotlinlang.org/spec/kotlin-spec.html Kotlin code used as an example for the killDataFlow inference analysis. It contains nested loops with assignments to x and y, which are used to illustrate where killDataFlow instructions would be inserted. ```kotlin var x: Int = 0 var y: Int = 0 while (b1) { y = f() do { x = g() } while (b2) } ``` -------------------------------- ### Declarations for operator interoperation example Source: https://kotlinlang.org/spec/kotlin-spec.html Declares types used to demonstrate how operator conventions interoperate: `A` supports increment, `B` supports indexed get/set returning `A`, and `C` supports indexed get returning `B`. The expression `C[0][0]++` is expanded step by step in the following examples. ```kotlin class A { operator fun inc(): A { ... } } object B { operator fun get(i: Int): A { ... } operator fun set(i: Int, value: A) { ... } } object C { operator fun get(i: Int): B { ... } } ``` -------------------------------- ### Function with map and filter Source: https://kotlinlang.org/spec/kotlin-spec.html Example of a function using map and filter on a list. ```kotlin fun f() = listOf(1, 2).map { it + 2 }.filter { it > 0 } ``` -------------------------------- ### Smart cast with require contract Source: https://kotlinlang.org/spec/kotlin-spec.html Example showing that the `require` contract smart-casts `x` to non-null after the check, making the addition legal. ```kotlin val x: Int? = ... // x is known to be non-null thanks to assume introduced by // the contract of require require(x != null) val y = x + 4 // would be illegal without contract ``` -------------------------------- ### Fully-qualified call example Source: https://kotlinlang.org/spec/kotlin-spec.html Illustrates a fully-qualified call: the overload candidate set contains all top-level callables with the specified name in the specified package, and the call `a.b.c.foo()` resolves among them. ```kotlin package a.b.c fun foo(a: Int) {} fun foo(a: Double) {} fun foo(a: List) {} val foo = {} . . . a.b.c.foo() ``` -------------------------------- ### Override visibility inheritance example Source: https://kotlinlang.org/spec/kotlin-spec.html Shows how overriding declarations inherit or weaken visibility from the base declaration. The example includes classes B, C, and D, where C inherits protected visibility and D explicitly declares public visibility, which is weaker than protected. The snippet also starts an open class P with an open function g, but the example is incomplete as provided. ```kotlin open class B { protected open fun f() {} } class C : B() { open override fun f() {} // `f` is protected, as its visibility is // inherited from the base declaration } class D : B() { public open override fun f() {} // this is correct, as public visibility is // weaker that protected visibility // from the base declaration } open class P { open fun g() {} } ``` -------------------------------- ### Effectively immutable smart cast sink examples Source: https://kotlinlang.org/spec/kotlin-spec.html Shows valid and invalid placements of direct and nested redefinitions relative to smart cast sinks. The functions named Ok satisfy the effectively immutable conditions, while the Bad functions violate them by placing a redefinition between the definition and the sink or after a nested sink. ```kotlin fun directSinkOk() { var x: Int? = 42 // definition if (x != null) // smart cast source x.inc() // direct sink run { x = null // nested redefinition } } fun directSinkBad() { var x: Int? = 42 // definition run { x = null // nested redefinition // between a definition // and a sink } if (x != null) // smart cast source x.inc() // direct sink } fun nestedSinkOk() { var x: Int? = 42 // definition x = getNullableInt() // direct redefinition run { if (x != null) // smart cast source x.inc() // nested sink } } fun nestedSinkBad01() { var x: Int? = 42 // definition run { if (x != null) // smart cast source x.inc() // nested sink } x = getNullableInt() // direct redefinition // after the nested sink } fun nestedSinkBad02() { var x: Int? = 42 // definition run { x = null // nested redefinition } run { if (x != null) // smart cast source x.inc() // nested sink } } ``` -------------------------------- ### Overload specificity example with f(Int, String) and f(Any?, CharSequence) Source: https://kotlinlang.org/spec/kotlin-spec.html Shows two overloaded functions where (1) is more specific than (2) because (1) can forward its arguments to (2) but not vice versa. Used to illustrate the rationale for choosing the most specific candidate from the overload candidate set. ```kotlin fun f(arg: Int, arg2: String) {} // (1) fun f(arg: Any?, arg2: CharSequence) {} // (2) ... f(2, "Hello") ``` -------------------------------- ### Transformed property access as getter functions Source: https://kotlinlang.org/spec/kotlin-spec.html Shows the equivalent transformed class AA where property access is replaced by synthetic getter functions a$get(). The example is incomplete in the source, but it illustrates the transformation described in the surrounding text. ```kotlin class AA { fun a$get(): Int = 5 // (1) fun Double.a$get(): Boolean // (2) = this != 42.0 fun test() { println(a$get()) // Resolves to (1) ``` -------------------------------- ### Function with labeled loop and break Source: https://kotlinlang.org/spec/kotlin-spec.html Example of a function with a labeled while loop and a break condition. ```kotlin fun f(x: Int) { var y = x loop@ while(y != 500) { y++ if(y % 20 == 3) break@loop } } ``` -------------------------------- ### Direct and nested smart cast sinks example Source: https://kotlinlang.org/spec/kotlin-spec.html Illustrates direct and nested smart cast sinks and redefinitions for a mutable local property. The comment markers identify each role: definition, nested sink, nested redefinition, direct sink, and direct redefinition. ```kotlin fun example() { // definition var x: Int? = null if (x != null) { run { // nested smart cast sink x.inc() // nested redefinition x = ... } // direct smart cast sink x.inc() } // direct redefinition x = ... } ``` -------------------------------- ### Smart cast with check contract Source: https://kotlinlang.org/spec/kotlin-spec.html Example showing that the `check` contract smart-casts `x` to `Int` after the check, making the addition legal. ```kotlin val x: Any = ... check(x is Int) // x is known to be Int thanks to assume introduced by // the contract of check val y = x + 4 // would be illegal without contract ``` -------------------------------- ### Kotlin this-expression example: interface B and object C Source: https://kotlinlang.org/spec/kotlin-spec.html Declares an interface B and an object C, used as a minimal example for labeled this-expressions in the Kotlin specification. ```kotlin interface B object C ``` -------------------------------- ### Callable references example with errors Source: https://kotlinlang.org/spec/kotlin-spec.html Illustrates callable references (`::`) for properties and functions, including type and value references. Shows that references to companion object members are forbidden, and that object types behave as values, causing errors when used as type references. ```kotlin class A { val a: Int = 42 fun a(): String = "TODO()" companion object { val bProp: Int = 42 fun bFun(): String = "TODO()" } } object O { val a: Int = 42 fun a(): String = "TODO()" } fun main() { // Error: ambiguity between two possible callables // val errorAmbiguity = A::a // Error: cannot reference companion object implicitly // val errorCompanion = A::bFun val aTypePropRef: (A) -> Int = A::a val aTypeFunRef: (A) -> String = A::a val aValPropRef: () -> Int = A()::a val aValFunRef: () -> String = A()::a // Error: object type behave as values // val oTypePropRef: (O) -> Int = O::a // Error: object types behave as values // val oTypeFunRef: (O) -> String = O::a val oValPropRef: () -> Int = O::a val oValFunRef: () -> String = O::a } ``` -------------------------------- ### Expansion of indexing expressions Source: https://kotlinlang.org/spec/kotlin-spec.html Third expansion step: the indexing expressions are expanded, resulting in the fully expanded form using `get` and `set` calls. ```kotlin C.get(0).set(C.get(0).get(0).inc()) ``` -------------------------------- ### When expression with bound value examples Source: https://kotlinlang.org/spec/kotlin-spec.html Shows when expressions with a bound value using type test conditions (is/!is) and containment test conditions (in/!in). The second when is non-exhaustive and causes a compile-time error. ```kotlin val a = 42 val b = -1 val l = (1..10).toList() when (a) { is Int, !is Int -> {} in l, !in l -> {} } // Error, as it is a non-exhaustive when expression val c = when (a) { is Int, !is Int -> {} in l, !in l -> {} } ``` -------------------------------- ### Parameterized classifier types: well-formed and ill-formed examples Source: https://kotlinlang.org/spec/kotlin-spec.html Illustrates well-formed and ill-formed parameterized classifier types. Shows valid type constructors with unbounded, projected, and bounded type parameters, plus invalid uses of a raw type as a supertype and a type argument that violates the upper bound. ```kotlin // A well-formed type constructor with no supertypes // A and B are unbounded type parameters interface Generic // A well-formed type constructor // with a single parameterized supertype // Int and String are well-formed concrete types interface ConcreteDerived : Generic // A well-formed type constructor // with a single parameterized supertype // P and Q are type parameters of GenericDerived, // used as type arguments of Generic interface GenericDerived : Generic // An ill-formed type constructor, // as abstract type Generic // cannot be used as a supertype interface Invalid

: Generic // A well-formed type constructor with no supertypes // out A is a projected type parameter interface Out // A well-formed type constructor with no supertypes // S : Number is a bounded type parameter // (S <: Number) interface NumberWrapper // A well-formed type constructor // with a single parameterized supertype // NumberWrapper is well-formed, // as Int <: Number interface IntWrapper : NumberWrapper // An ill-formed type constructor, // as NumberWrapper is an ill-formed parameterized type // (String not(<:>) Number) interface InvalidWrapper : NumberWrapper ``` -------------------------------- ### Conditional expression with unknown types Source: https://kotlinlang.org/spec/kotlin-spec.html Example expression used to illustrate how the constraint system derives type relations for a conditional expression with unknown types. ```kotlin val e = if (c) a else b ``` -------------------------------- ### Overloaded functions for callable reference resolution Source: https://kotlinlang.org/spec/kotlin-spec.html Defines two overloaded functions `foo` used in the following callable reference example. ```kotlin fun foo(i: Int): Int = 2 // (1) fun foo(d: Double): Double = 2.0 // (2) ``` -------------------------------- ### Default argument evaluation order example Source: https://kotlinlang.org/spec/kotlin-spec.html Shows evaluation order for default arguments: explicit arguments are evaluated left-to-right, then missing defaults are evaluated in declaration order. The comments show the temporary variables and the final call. ```kotlin fun f(x: Int = h(), y: Int = g()) ... f() // $1 = h(); $2 = g(); $result = f($1, $2) f(m(), n()) // $1 = m(); $2 = n(); $result = f($1, $2) f(y = n(), x = m()) // $1 = n(); $2 = m(); $result = f($2, $1) f(y = n()) // $1 = n(); $2 = h(); $result = f($2, $1) ``` -------------------------------- ### Labeled and non-labeled return in lambdas Source: https://kotlinlang.org/spec/kotlin-spec.html Shows how non-labeled return inside a lambda returns from the outer function, while a labeled return returns from the nearest matching label. The example uses nested run calls with the same label b. ```kotlin // kotlin.run is a standard library inline function // receiving a lambda parameter fun foo() { // (1) run b@ { // (2) run b@ { // (3) return; // returns from (1) } } } fun bar() { // (1) run b@ { // (2) run b@ { // (3) return@b; // returns from (3) } } } ``` -------------------------------- ### String concatenation with safe calls and Elvis operator Source: https://kotlinlang.org/spec/kotlin-spec.html Shows string concatenation with safe calls and the Elvis operator to produce a default "null" string. The example is from the section on coercion to kotlin.Unit and is marked as equivalent to the preceding expression. ```kotlin val a = "Hello, " + (x?.toString() ?: "null") + " is " + (foo()?.toString() ?: "null") val b = "\nHello, " + (x?.toString() ?: "null") + "\nis \"" + (foo()?.toString() ?: "null") + "\"\n" ``` -------------------------------- ### When expression without bound value examples Source: https://kotlinlang.org/spec/kotlin-spec.html Illustrates when expressions without a bound value. The first when is used as a statement, the second (without else) causes a compile-time error because it is non-exhaustive, the third includes an else branch, and the last shows multiple conditions. ```kotlin val a = 42 val b = -1 when { a == b -> {} a != b -> {} } // Error, as it is a non-exhaustive when expression val c = when { a == b -> {} a != b -> {} } val d = when { a == b -> {} a != b -> {} else -> {} } when { a == b || a != b -> {} 42 > 0 -> {} } ``` -------------------------------- ### Simple classifier type examples Source: https://kotlinlang.org/spec/kotlin-spec.html Shows well-formed and ill-formed simple classifier types. The first two interfaces are valid, while `Invalid` is ill-formed because a nullable type cannot be a supertype. ```kotlin // A well-formed type with no supertypes interface Base // A well-formed type with a single supertype Base interface Derived : Base // An ill-formed type, // as nullable type cannot be a supertype interface Invalid : Base? ``` -------------------------------- ### Delegating properties to a MutableMap Source: https://kotlinlang.org/spec/kotlin-spec.html Example of delegating properties to a MutableMap. Defines getValue and setValue operators for Map and MutableMap, then uses them in handleConfig to read and write properties backed by the map. ```kotlin operator fun Map.getValue( thisRef: Any?, property: KProperty<*>): R = getOrElse(property.name) { throw NoSuchElementException() } as R operator fun MutableMap.setValue( thisRef: Any?, property: KProperty<*>, newValue: V) = set(property.name, newValue) fun handleConfig(config: MutableMap) { val parent by config // Any? val host: String by config // String var port: Int by config // Int // Delegating property accesses to Map.getValue // Throwing NSEE as there is no "port" key in the map // println("$parent: going to $host:$port") // Delegating property access to Map.setValue port = 443 // Map now contains "port" key // Delegating property accesses to Map.getValue // Not throwing NSEE as there is "port" key in the map println("$parent: going to $host:$port") } ``` -------------------------------- ### Integer literal types as intersection and union Source: https://kotlinlang.org/spec/kotlin-spec.html Shows how integer literal types (ILT) can be treated as intersection types (allowing Int and Short assignments) or as union types (enabling contravariant position usage). The example defines an In interface and a select function to illustrate both behaviors. ```kotlin interface In fun T.asIn(): In = ... fun select(a: S, b: In): S = ... fun iltAsIntersection() { val a: Int = 42 // ILT(Byte, Short, Int, Long) <: Int fun foo(a: Short) {} foo(1377) // ILT(Short, Int, Long) <: Short } fun iltAsUnion() { val a: Short = 42 select(a, 1337.asIn()) // For argument a: // Short <: S // For argument b: // In <: In => // S <: ILT(Short, Int, Long) // Solution: S =:= Short } ``` -------------------------------- ### Declaration-site variance with invariant, out, and in type parameters Source: https://kotlinlang.org/spec/kotlin-spec.html Shows how to declare invariant, covariant (out), and contravariant (in) type parameters in interfaces and how they affect subtyping assignments. Invariant parameters do not create subtyping; covariant parameters create same-way subtyping; contravariant parameters create opposite-way subtyping. The example uses placeholder expressions (...) and a random condition to illustrate allowed and error assignments. ```kotlin // A type constructor with an invariant type parameter interface Invariant // A type constructor with a covariant type parameter interface Out // A type constructor with a contravariant type parameter interface In fun testInvariant() { var invInt: Invariant = ... var invNumber: Invariant = ... if (random) invInt = invNumber // ERROR else invNumber = invInt // ERROR // Invariant type parameters do not create subtyping } fun testOut() { var outInt: Out = ... var outNumber: Out = ... if (random) outInt = outNumber // ERROR else outNumber = outInt // OK // Covariant type parameters create "same-way" subtyping // Int <: Number => Out <: Out // (more specific type Out can be assigned // to a less specific type Out) } fun testIn() { var inInt: In = ... var inNumber: In = ... if (random) inInt = inNumber // OK else inNumber = inInt // ERROR // Contravariant type parameters create "opposite-way" subtyping // Int <: Number => In :> In // (more specific type In can be assigned // to a less specific type In) } ``` -------------------------------- ### Class declaration with init blocks Source: https://kotlinlang.org/spec/kotlin-spec.html Class declaration with declarations and init blocks. Control flow is propagated through every element in order of appearance. ```kotlin class A (...) { 'declaration 1' 'declaration 2' 'init-block 1' 'declaration 3' 'init-block 2' ... } ``` -------------------------------- ### kotlin.Enum ordinal property Source: https://kotlinlang.org/spec/kotlin-spec.html Property of kotlin.Enum that contains the ordinal (position starting from zero) of the enumeration constant. ```kotlin public final val ordinal: Int ``` -------------------------------- ### Class implementing Comparable with swap and compareTo Source: https://kotlinlang.org/spec/kotlin-spec.html Shows a class implementing the Comparable interface, with a swap function and an override of compareTo. Demonstrates a class with a primary constructor and a supertype specifier. ```kotlin class Pair(val a: Int, val b: Int) : Comparable { fun swap(): Pair = Pair(b, a) override fun compareTo(other: Pair): Int { val f = a.compareTo(other.a) if (f != 0) return f return b.compareTo(other.b) } } ``` -------------------------------- ### Continuation resume and resumeWithException extension functions Source: https://kotlinlang.org/spec/kotlin-spec.html Extension functions on Continuation that avoid explicitly creating a Result when calling resumeWith. Use resume(value: T) to resume with a successful value and resumeWithException(exception: Throwable) to resume with an exception. ```kotlin fun Continuation.resume(value: T) fun Continuation.resumeWithException(exception: Throwable) ``` -------------------------------- ### Nullable type subtyping rules with Foo and Bar Source: https://kotlinlang.org/spec/kotlin-spec.html Illustrates subtyping for nullable types using two classes: Foo with B : A? and Bar with B : A. Each class shows which assignments are allowed (OK) or rejected (ERROR) based on the nullability subtyping rules and regular subtyping. ```kotlin class Foo { val b: B = mk() val bQ: B? = mk() // For this assignment to be well-formed, // B must be a subtype of A // Subtyping by nullability holds per rule 4 // Regular subtyping does not hold, // as B <: A? is not enough to show B <: A // (we are missing B!! <: A!!) val ab: A = b // ERROR // For this assignment to be well-formed, // B? must be a subtype of A // Subtyping by nullability does not hold per rule 5 val abQ: A = bQ // ERROR // For this assignment to be well-formed, // B must be a subtype of A? // Subtyping by nullability holds per rule 3 // Regular subtyping does hold, // as B <: A? is enough to show B <: A? val aQb: A? = b // OK // For this assignment to be well-formed, // B? must be a subtype of A? // Subtyping by nullability holds per rule 3 // Regular subtyping does hold, // as B <: A? is enough to show B? <: A? // (taking the upper edge of the nullability lozenge) val aQbQ: A? = bQ // OK } class Bar { val b: B = mk() val bQ: B? = mk() // For this assignment to be well-formed, // B must be a subtype of A // Subtyping by nullability holds per rule 4 // Regular subtyping does hold, // as B <: A is enough to show B <: A val ab: A = b // OK // For this assignment to be well-formed, // B? must be a subtype of A // Subtyping by nullability does not hold per rule 5 val abQ: A = bQ // ERROR // For this assignment to be well-formed, // B must be a subtype of A? // Subtyping by nullability holds per rule 3 // Regular subtyping does hold, // as B <: A is enough to show B <: A? // (taking the upper triangle of the nullability lozenge) val aQb: A? = b // OK // For this assignment to be well-formed, // B? must be a subtype of A? // Subtyping by nullability holds per rule 3 // Regular subtyping does hold, // as B <: A is enough to show B? <: A? // (taking the upper edge of the nullability lozenge) val aQbQ: A? = bQ // OK } ``` -------------------------------- ### Callable reference as argument to overloaded call Source: https://kotlinlang.org/spec/kotlin-spec.html Shows that when a callable reference is passed as an argument, the expected parameter type guides resolution to the `Double` overload. ```kotlin fun bar(f: (Double) -> Double) {} bar(::foo) ``` -------------------------------- ### Data class declaration and equivalent explicit implementation Source: https://kotlinlang.org/spec/kotlin-spec.html Shows a data class declaration and its equivalent explicit class implementation, illustrating how equals, hashCode, toString, componentN, and copy are generated. The explicit version is provided for illustration and may not exactly match compiler-generated code. ```kotlin data class DC(val x: Int, val y: Double) ``` ```kotlin class DC(val x: Int, val y: Double) { override fun equals(other: Any?): Boolean { if(other !is DC) return false return x == other.x && y == other.y } override fun hashCode(): Int = x.hashCode() + 31 * y.hashCode() override fun toString(): String = "DC(x=$x,y=$y)" operator fun component1(): Int = x operator fun component2(): Double = y fun copy(x: Int = this.x, y: Double = this.y): DC = DC(x, y) } ``` -------------------------------- ### Lambda expansion with componentN calls Source: https://kotlinlang.org/spec/kotlin-spec.html Shows the expansion of a lambda with a single implicit parameter `$tmp` into a block that calls `component1()` and `component3()` on that parameter. The ellipsis represents the original lambda body. ```kotlin foo { $tmp -> val x: A = $tmp.component1() val z = $tmp.component3() ... } ``` -------------------------------- ### Return with value and throw statements Source: https://kotlinlang.org/spec/kotlin-spec.html Return with value, labeled return with value, and throw statements used in control-flow graph analysis. ```kotlin return a return@label a throw a ``` -------------------------------- ### Delegated property declaration and expansion Source: https://kotlinlang.org/spec/kotlin-spec.html Shows the delegated property declaration and its expansion. The first block is the delegated declaration; the second shows the equivalent expansion using a delegate and a getter; the third shows the overloadable form of every access to the property. The delegatee may be provided by provideDelegate. ```kotlin val x: T by e ``` ```kotlin val x$delegate = e val x: T get(): T = x$delegate.getValue(thisRef, ::x) ``` ```kotlin e.getValue(thisRef, property) ``` -------------------------------- ### Primary constructor parameter expansion Source: https://kotlinlang.org/spec/kotlin-spec.html Shows the syntactic expansion of primary constructor parameters: property parameters (val/var) are equivalent to regular parameters plus property declarations in the class body. The first class uses property parameters directly; the second shows the expanded form with explicit properties. ```kotlin class Foo(i: Int, vararg val d: Double, var s: String) : Super(i, d, s) {} class Foo(i: Int, vararg d_: Double, s_: String) : Super(i, d_, s_) { val d = d_ var s = s_ } ``` -------------------------------- ### Inheritance delegation with `by` and its expansion Source: https://kotlinlang.org/spec/kotlin-spec.html Illustrates inheritance delegation using the `by` keyword in a class header. The first block shows the delegation syntax; the second shows the expansion where the delegate is stored in a synthetic property `I$delegate`. The delegate expression cannot access the classifier's properties or methods except primary constructor parameters. ```kotlin interface I { fun foo(value: Int): Double val bar: Long } interface J : I { fun fee(): Int } class C(delegatee: I): I by delegatee ``` ```kotlin interface I { fun foo(value: Int): Double val bar: Long } interface J : I { fun fee(): Int } class C(delegatee: I): I { val I$delegate = delegate ``` -------------------------------- ### Local class declaration capturing a value Source: https://kotlinlang.org/spec/kotlin-spec.html Declares a local class inside a function that captures a value from the enclosing scope. The example shows that the local class can access the local variable x and that the resulting property y equals 2. ```kotlin fun foo() { val x = 2 class Local { val y = x } Local().y // 2 } ``` -------------------------------- ### Data class with explicified equals and toString and equivalent implementation Source: https://kotlinlang.org/spec/kotlin-spec.html Shows a data class with explicified equals and toString, and its equivalent explicit class implementation. Note that hashCode, component1, and copy are still generated because they are not explicified. ```kotlin data class DC(val x: Int) { override fun equals(other: Any?) = false override fun toString(): String = super.toString() } ``` ```kotlin class DC(val x: Int) { override fun equals(other: Any?) = false override fun hashCode(): Int = x.hashCode() override fun toString(): String = super.toString() operator fun component1(): Int = x fun copy(x: Int = this.x): DC = DC(x) } ``` -------------------------------- ### Overload resolution with explicit lambda parameter Source: https://kotlinlang.org/spec/kotlin-spec.html Shows a successful overload resolution when the lambda has an explicit parameter, making only the overload with a one-parameter lambda applicable. The example is annotated with @OverloadResolutionByLambdaReturnType and demonstrates that the lambda's parameter list disambiguates the call. ```kotlin @OverloadResolutionByLambdaReturnType fun foo(cb: Unit.() -> String) = Unit // (1) @OverloadResolutionByLambdaReturnType fun foo(cb: (Unit) -> Int) = Unit // (2) fun testOk02() { val take = Unit foo { a -> 42 } // Only (2) is applicable // as its lambda takes one parameter } ``` -------------------------------- ### Property access resolution in class A Source: https://kotlinlang.org/spec/kotlin-spec.html Shows how property access is resolved in a class with both a regular property and an extension property. The comments indicate which property each access resolves to, demonstrating that the receiver and explicit qualifier affect resolution. ```kotlin class A { val a: Int = 5 // (1) val Double.a: Boolean // (2) get() = this != 42.0 fun test() { println(a) // Resolves to (1) with(42.0) { println(this@A.a) // Resolves to (1) println(this.a) // Resolves to (2) println(a) // Resolves to (2) } } } ``` -------------------------------- ### kotlin.Iterator.next(): T Source: https://kotlinlang.org/spec/kotlin-spec.html Returns the next element in the sequence. ```APIDOC ## kotlin.Iterator.next(): T ### Description Returns the next element in the sequence. ### Method operator fun next(): T ### Response #### Success Response - **T** - The next element in the sequence. ``` -------------------------------- ### Forwarding arguments between overloads f1 and f2 Source: https://kotlinlang.org/spec/kotlin-spec.html Demonstrates that the more specific function f1 can forward its arguments to f2, while the reverse is invalid because f1 is not applicable for the arguments of f2. This supports the rationale for choosing the most specific candidate. ```kotlin fun f1(arg: Int, arg2: String) { f2(arg, arg2) // VALID: can forward both arguments } fun f2(arg: Any?, arg2: CharSequence) { f1(arg, arg2) // INVALID: function f1 is not applicable } ``` -------------------------------- ### Lambda body with multiple suspension points Source: https://kotlinlang.org/spec/kotlin-spec.html Example lambda body with multiple suspension points, used to illustrate the state machine transformation. Each suspending call (await()) is a suspension point; the compiler generates states for each suspension point and each non-suspending return statement. ```kotlin // Lambda body with multiple suspension points val a = a() val y = foo(a).await() // suspension point #1 b() val z = bar(a, y).await() // suspension point #2 c(z) ``` -------------------------------- ### Inline, crossinline, and noinline parameter usage rules Source: https://kotlinlang.org/spec/kotlin-spec.html Illustrates the allowed and disallowed uses of inline, crossinline, and noinline parameters inside an inline function. Comments mark calls that are not allowed. ```kotlin fun bar(value: Any?) {} inline fun inlineParameter(arg: () -> Unit) { arg() } inline fun noinlineParameter(noinline arg: () -> Unit) { arg() } inline fun crossinlineParameter(crossinline arg: () -> Unit) { arg() } inline fun foo(inl: () -> Unit, crossinline cinl: () -> Unit, noinline noinl: () -> Unit) { // all arguments may be called inl() cinl() noinl() // all arguments may be passed as inline inlineParameter(inl) inlineParameter(cinl) inlineParameter(noinl) // only noinline arguments may be passed as noinline noinlineParameter(inl) // not allowed noinlineParameter(cinl) // not allowed noinlineParameter(noinl) // noinline/crossinline arguments may be passed as crossinline crossinlineParameter(inl) // not allowed crossinlineParameter(cinl) crossinlineParameter(noinl) // only noinline arguments may be passed to non-inline functions bar(inl) // not allowed bar(cinl) // not allowed bar(noinl) // noinline/crossinline parameters may be captured in lambda literals bar({ inl() }) // not allowed bar({ cinl() }) bar({ noinl() }) } ``` -------------------------------- ### Safe navigation expansion Source: https://kotlinlang.org/spec/kotlin-spec.html Shows the expansion of a safe navigation expression `a?.c` into a `when` expression that checks for null and otherwise evaluates `$tmp.c`. ```kotlin when(val $tmp = a) { null -> null else -> { $tmp.c } } ``` -------------------------------- ### Construct functional interface via conversion-like calls Source: https://kotlinlang.org/spec/kotlin-spec.html Demonstrates conversion-like function calls where a functional interface name is used as the function being called, allowing construction of interface instances from lambdas or function values. ```kotlin fun interface FI { fun bar(s: Int): Int } fun foo() { val fi = FI { it } val fi2 = FI { s: Int -> s + 42 } val fi3 = FI { s: Number -> s.toInt() } val fi4 = FI({ it }) val lambda = { s: Int -> s + 42 } val fi5 = FI(lambda) } ``` -------------------------------- ### Provided delegate read-only property expansion Source: https://kotlinlang.org/spec/kotlin-spec.html Shows a delegated read-only property using provideDelegate and its equivalent expansion. The provided delegate is obtained via e.provideDelegate. ```kotlin val x: T by e ``` ```kotlin val x$delegate = e.provideDelegate(thisRef, ::x) val x: T get(): T = x$delegate.getValue(thisRef, ::x) ``` -------------------------------- ### Default parameters in Kotlin function calls Source: https://kotlinlang.org/spec/kotlin-spec.html Shows how default parameter values are used when arguments are omitted. The example marks the call `bar(2, "Me")` as invalid because a default value cannot be used for a positional argument in the middle of the argument list. Defaults are used only for missing trailing arguments or when a named argument is omitted. ```kotlin fun bar(a: Int = 1, b: Double = 42.0, s: String = "Hello"): Double = a + b + s.toDouble() fun main(args: Array) { // Valid call, all default parameters used println(bar()) // Valid call, defaults for `b` and `s` used println(bar(2)) // Valid call, default for `b` used println(bar(2, s = "Me")) // Invalid call, default for `b` cannot be used println(bar(2, "Me")) } ``` -------------------------------- ### Logical AND operator Source: https://kotlinlang.org/spec/kotlin-spec.html Logical AND operator used in control-flow graph analysis. ```kotlin x && y ``` -------------------------------- ### Compiled loop form of tail-recursive factorial Source: https://kotlinlang.org/spec/kotlin-spec.html Illustrates the loop form that a tail-recursive function like `factorialTC` should be compiled to by the platform. ```kotlin fun factorialLoop(i: Int, result: Int = 1): Int { var $i: Int = i var $result: Int = result while(true) { if ($i == 0) return $result else { $i = $i - 1 $result = $i * $result } } } ``` -------------------------------- ### Labeled do-while loop Source: https://kotlinlang.org/spec/kotlin-spec.html Labeled do-while loop. ```kotlin loop@ do { b... } while(c) ```