Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

366
Visualizações
Why safe call (?.) is needed on a layout binding variable?

I am working with the codelab:

https://developer.android.com/codelabs/kotlin-android-training-data-binding-basics?index=..%2F..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?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda