What is the best way to declare on UI component in android with Kotlin?

Udi :

I'm trying to build android application using Kotlin for the first time.

I want to declare on some buttons outside the OnCreate method and i can initialize them only Inside this function with findViewById.

Can i declare in simple and clean code like in java?

private Button btnProceed;

Because when converting it to Kotlin it look like:

private var btnProceed: Button? = null

And then when initialize OnClick function need to add ! sign:

btnProceed!!.setOnClickListener

What is the right and cleanest way?

zsmb13 :

This is a good use case for lateinit. Marking a property lateinit allows you to make it non nullable, but not assign it a value at the time that your Activity's constructor is called. It's there precisely for classes like Activities, when initialization happens in a separate initializer method, later than the constructor being run (in this case, onCreate).

private lateinit var btnProceed: Button

If the property is read before a real value is assigned to it, it will throw an exception at runtime - by using lateinit, you're taking the responsibility for initializing it before you access it for the first time.


Otherwise, if you want the compiler to guarantee safe access for you, you can make the Button nullable as the converter does by default. Instead of the unsafe !! operator though, which the converter often uses, you should use the safe call operator where you access the property:

btnProceed?.setOnClickListener { ... }

This will make a regular call if btnProceed is a non-null value, and do nothing otherwise.


On a final note, you can check out Kotlin Android Extensions, which eliminates the need to create properties for your Views altogether, if it works for your project.


Last edit (for now): you should also look at using lazy as described in the other answers. Being lazy is cool.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=433140&siteId=1