简体   繁体   中英

Without late initialization, why can't we declare a top-level property in kotlin?

Why isn't this possible?

Declaring a top level property without using late initialization technique and assigning value to that variable in OnCreate(Bundle?)..

class MainActivity : AppCompatActivity() {

private var variable : Int

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    
    variable = 10
}
}

You can do it but then you need init block

class MainActivity : AppCompatActivity() {

private var variable : Int

init {
        variable=10
    }

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    
    variable = 10
}
}

First of all you should know that in Kotlin, when we declare a variable we have to initialize it with a value or we need to assign null .

But if we don't want to initialize the variable with null or any value. Rather we want to initialize it in future with a valid value, then we have to use lateinit. Actually it is a promise to compiler that the value will be initialized in future. .

But what you want to declare variable without lateinit ?

Then game changer lazy keyword will come.

but there is one drawback and that is Every lazy property is a val (immutable) property and cannot be changed once assigned.

so is there is certain condition that your value is fix and don't want to change it the n use lazy keyword.

otherwise you should initialize any default value without use of lateinit keyword.

like, private var number: Int = 0 or private var name: String = "" and the you can change it in onCreate() too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM