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

Time:02-04

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
}
}

CodePudding user response:

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
}
}

CodePudding user response:

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.

  •  Tags:  
  • Related