Import kotlinx.android.synthetic.main.activity_main.*

I recently learned that some Kotlin plugins allow for accessing view names from XML directly in Kotlin. This alleviates the need to create widgets in Kotlin and use “findViewByID” to initialize them. However, the Android Programming 4th edition book does not take advantage of this shortcut and does create the widgets, etc. So I have a two part question:

  1. Are there any disadvantages to using the plug-in/shortcut? Or stated another way, are there any advantages to actually creating and initializing the widgets?
  2. I was able to use the shortcut without the import statement in the subject, and I’m not sure why it worked. Here are my imports:
    import android.os.Bundle
    import android.text.Editable
    import android.text.TextWatcher
    import android.view.LayoutInflater
    import android.view.View
    import android.view.ViewGroup
    import android.widget.Button
    import android.widget.EditText
    import androidx.fragment.app.Fragment
    So why did it work WITHOUT the import kotlinx.android.synthetic.main.activity_main.* ?

Thanks in advance!

I cannot fully answer the questions here, but I am also interested in the reasoning why this decision was made.

Much of the ease / speedup that Kotlin provides over Java when coding is implemented by overhead on the backend. The shortcut works because when the Kotlin code gets compiled down in to bytecode, it internally is calling findViewById against a cache.

However, you must be very careful where in the lifecycle you use the shortcut, it must be after the view has been created. This becomes even more important later on when Fragments are introduced. This may be some of the reasoning why it was avoided and findViewById was kept in.

Import the synthetic properties in the MainActivity. Add the following line at the end of the onCreate method.