Kotlin Code Initialization from the following place will do in given below order
class body
init body of single in class
init body of multiple in class then it follows the order in which it been written
constructor body of primary
constructor body of other than primary will get called in the order it linked and invoked/called while object creation by user
Note: body means here is opening curly bracket and closing curly bracket like { } with proper kotlin syntax
Now let’s understand by code open REPL and write the below code and run
you can use play ground for kotlin language click me to try
class B{ companion object{ fun firstInit():Int{ println("firstInit\n") return 20 } } } class A{ var i=B.firstInit() val va: Int constructor(){ va=10 println("c= i:$i\n") i=2 println("ci= i:$i\n") } init { println("i1= i:$i\n") } init { i=1 println("i2= after i:$i\n") } fun see(){ println("f= i:$i\n") } constructor(a:Int):this(){ println("After primary= i:$i and before secondary init\n") i=a println("after secondary init c2= i:$i\n") //va=20 } } fun main(){ A().see() } main()
Output when primary constructor A().see() is called observe the execution sequence
firstInit
i1= i:20
i2= after i:1
c= i:1
ci= i:2
f= i:2
Output, when secondary linked with primary constructor A(40).see(), is called observe the execution sequence
firstInit
i1= i:20
i2= after i:1
c= i:1
ci= i:2
After primary= i:2 and before secondary init
after secondary init c2= i:40
f= i:40
if all constructor is independent i.e not calling the other constructor from within then that constructor will get called and its output will be like primary only as per above code because the primary is not invoking any other constructor but the secondary is doing it.
Point to keep in mind while playing with Val variable initialization in kotlin
You might have seen val va: Int
if you have initialized val variable in the init{} body then it’s not compulsory to do in any of constructor unless you have a requirement but at only one placeclass A{
val i:Int
init {
i=10
}
fun see(){
println("fi:$i")
}
constructor(){
println("ci:$i")
}
constructor(ii:Int):this(){
println("ci:$i")
}
}
A().see()
so any val variable if you declare in class body and not initialized in init {} body then
you have to do the initialization in all of the constructors you have in class
only if not linked/invoked within class see example below else you will be in trouble
class A{
val i:Int
init {
// i=10
}
fun see(){
println("fi:$i")
}
constructor(){ i=10
println("ci:$i")
}
constructor(ii:Int){ i=ii
println("ci:$i")
}
}
A().see()
In case of linked primary constructor initializes it is fine else in all constructor
class A{
val i:Int
init {
// i=10
}
fun see(){
println("fi:$i")
}
constructor(){ i=10
println("ci:$i")
}
constructor(ii:Int):this(){ //i=ii// not compulsory unless you have requirement as such any, as init it is done in primary constructor
println("ci:$i")
}
}
A().see()
or you can initialize then and there in the class body like val va: Int=10
Point to remember about the Lateinit
lateinit var lv:String
if you have initialized lateinit var variable in the init{} body then it’s not compulsory to do in any of constructor unless you have a requirement
class A{
lateinit var i:String
init {
i="10"
}
fun see(){
println("fi:$i")
}
constructor(){ //i="10"
println("ci:$i")
}
constructor(ii:String):this(){ //i=ii// not compulsory unless you have requirement as such any,as init it is done in primary constructor
println("ci:$i")
}
}
so any lateinit var variable if you declare in class body and not initialized in init {} body then
you have to do the initialization in all of the constructors you have in class
only if not linked/invoked within class see example below else you will be in trouble
class A{
lateinit var i:String
init {
//i="10"
}
fun see(){
println("fi:$i")
}
constructor(){ i="10"
println("ci:$i")
}
constructor(ii:String){ i=ii
println("ci:$i")
}
}
In case of linked primary constructor initializes it is fine else in all constructor
class A{
lateinit var i:String
init {
//i="10"
}
fun see(){
println("fi:$i")
}
constructor(){ i="10"
println("ci:$i")
}
constructor(ii:String) :this(){ // i=ii // not compulsory unless you have requirement as such any,as init it is done in primary constructor
println("ci:$i")
}
}
lateinit var variable applied only on Objects not on primitive type
error: ‘lateinit’ modifier is not allowed on properties of primitive types
lateinit var i:Int
/**
* You can edit, run, and share this code.
* play.kotlinlang.org
*/
class D{
companion object{
fun firstInit():Int{
println("firstInit\n")
return 20
}
init{
println("companion Init\n")
}
//println("cb firstInit\n")
}
var title1="title1 test"
var title="ztd naaval class also".also(::println)
constructor(title:String){
this.title=title
println("constructor title:${this.title}")
var selected="2353 2014"
if (!isMatch(selected)){
println("go for check ")
}else{
println("not going for check ")
}
}
init{
title="chnage in init"
println("D init:"+title)
}
private val jokerList = arrayOf("2014","2353")
private fun isMatch(vin:String) : Boolean {
return jokerList.contains(vin)
}
}
//println("first class")
fun main() {
val sl=mutableListOf<String>("1","2","3")
sl.add("apple")
sl.add("naval")
sl.add("app")
val sl1 =arrayOf<String>("1","2","3")
var chkstr="1"
var chk= chkstr !in sl
println("$chkstr is not in $sl is $chk")
chkstr="0"
chk= chkstr in sl
println("$chkstr is in $sl is $chk")
val list=mutableListOf<Int>(2)
list[0]=1
try{
val i=list[-1]
}catch(e:Exception){
println("Exception:${e.message} :$list ")
}
data class P1(val name:String)
data class P2(val i:Int)
var p1 :P1? = P1("naval")
//p1=null
p1?.let{
println("null case ${it}")
}
var a=ArrayList<Int>()
a.add(1)
a.add(12)
a.addAll(ArrayList<Int>().apply{ this.add(3)})
println(a.toString())
val res=(p1 as? P2)
println("Hello, world!!! res:${res} contains:${p1?.name?.contains("VA")}")
val d= D("ztf")
println("main fun title of D is called:"+d.title)
}