Home > front end >  Why safe call (?.) is needed on a layout binding variable?
Why safe call (?.) is needed on a layout binding variable?

Time:10-30

I am working with the codelab:

https://developer.android.com/codelabs/kotlin-android-training-data-binding-basics?index=../..android-kotlin-fundamentals#3

class MainActivity : AppCompatActivity() {
  private val myName: MyName = MyName("Aleks Haecky")
  ...

the MyName class:

data class MyName(var name: String = "", var nickname: String = "")

databinding variable in the layout:

<data>
    <variable
        name="myName"
        type="com.example.aboutme.MyName" />
</data>

the code in main activity where an an event handler is set

...
    binding.doneButton.setOnClickListener {
        addNickname(it)
    }
}

private fun addNickname(view: View) {
    binding.apply {
        myName.nickname = nicknameEdit.text.toString()
...

why does the variable myName generate the following error?

Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type MyName?

myName is not declared nullable. So why myName?.nickname is needed?

CodePudding user response:

it's because the variable myName in

binding.apply {
   myName?.nickname = nicknameEdit.text.toString()
   invalidateAll()
   ...
}

is not refers to this

private val myName: MyName = MyName("Aleks Haecky")

but it refers to the myName in this xml

<data>
    <variable
        name="myName"
        type="com.example.aboutme.MyName" />
</data>

And all variables that you define on layout xml file are nullable. That's why you need a safe call (?.) every time you want to access it.

  • Related