Home > Mobile >  How am I able to use some variables without initialization in Android
How am I able to use some variables without initialization in Android

Time:11-23

In the below example how is the "arguments" variable working as it is never initialized .

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

CodePudding user response:

This goes back to the basic Kotlin knowledge. The safe call operator ?. is there to specify that, if arguments is null, then let {...} will not be executed.

This is similar to what we do in Java:

if (arguments != null) {
    param1 = arguments.getString(ARG_PARAM1)
    param2 = arguments.getString(ARG_PARAM2)
}

CodePudding user response:

arguments is a property, not a variable. You can access properties of any ancestor class if they are not marked private or in some cases internal. In this case, the property is defined in a Java class. Java doesn't officially have properties, but Kotlin converts Java bean syntax into properties if the signatures are appropriate, as explained here.

Since the superclass Fragment defined in Java has a getArguments() method, that is converted to a property named arguments in Kotlin code.

  • Related