Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

374
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda