Skip to content

Instantly share code, notes, and snippets.

@ajalt
Created September 21, 2016 17:39
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ajalt/17645d90427774a0fca3048a6c7482e2 to your computer and use it in GitHub Desktop.
Save ajalt/17645d90427774a0fca3048a6c7482e2 to your computer and use it in GitHub Desktop.
Kotlin initializer order example
open class Parent {
private val a = println("Parent.a")
constructor(arg: Unit=println("Parent primary constructor default argument")) {
println("Parent primary constructor")
}
init {
println("Parent.init")
}
private val b = println("Parent.b")
}
class Child : Parent {
val a = println("Child.a")
init {
println("Child.init 1")
}
constructor(arg: Unit=println("Child primary constructor default argument")) : super() {
println("Child primary constructor")
}
val b = println("Child.b")
constructor(arg: Int, arg2:Unit= println("Child secondary constructor default argument")): this() {
println("Child secondary constructor")
}
init {
println("Child.init 2")
}
}
@rjhdby
Copy link

rjhdby commented May 29, 2017

maybe add some lazy initialization?

fun main(args: Array<String>) {
    Child().lazyVal
}

open class Parent {
    private val a = println("Parent.a")
    
    public val lazyVal by lazy {
        println("Parent.lazy")
    }
.......

@gronostajo
Copy link

Here's the output from ideone.com:

Child primary constructor default argument
Parent primary constructor default argument
Parent.a
Parent.init
Parent.b
Parent primary constructor
Child.a
Child.init 1
Child.b
Child.init 2
Child primary constructor

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment