Sushant kumar Sushant kumar - 1 year ago 194
Android Question

How to initialize widgets in android using kotlin

I have started to learn using kotlin language in android and getting problem while initialising my button variable ,because at the time of define my variable it ask to give some initial value when I initialize with null value and bind the variable in oncreate function its gives


here is my code

class AddsFragment : Fragment() {

var Add: Button = null!!

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val Rootview = inflater!!.inflate(R.layout.clubsfragment, null, false)
Add = Rootview.findViewById( as Button
return Rootview

Answer Source

The !! operators checks if the receiver is null and if it is throws KotlinNullPointerException. So null!! will always throw an exception.

You can achieve what you want in the following ways:

  1. Set a type of the property to Button?. In this case when accessing button's methods you will have to use either ? or !!.

    var add: Button? = null
    // Initialize it somewhere.
    add?.setText("Text") // Calls setText if Add != null
    add!!.setText("Text") // Throws an exception if Add == null
  2. Make the button a lateinit property.

    lateinit var add: Button
  3. Make the button a notNull delegate property.

    var add: Button by Delegates.notNull()

In the last two cases you cannot check if the button is null. If you need null comparison to work for the variable use the first approach.

There're another approaches which I'm not going to describe in details in this answer. The first on is using Kotlin Android Extensions. That's a compiler plugin that generates synthetic properties for your views so you don't need to call findViewById() and can access views with using generated properties.

The second way is to create your own delegate that will call findViewById() for you. It may look something like this:

val add: Button by bindView(

You can find an example of such delegate in the KotterKnife project.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download