-1

The Fragment class appears to have .setArgument() and .getArgument() methods, but no .arguments property. Why am I able to access such an argument?

var inputFragment: InputFragment = InputFragment()
inputFragment.arguments = intent.extras

Similarly, I am able to access what appears to be an .intent property within an Activity. Control-clicking on these classes leads me to the get methods for these "properties" within a .java file.

Cloud
  • 938
  • 1
  • 8
  • 24
  • 1
    Does this answer your question? [Getters and Setters in Kotlin](https://stackoverflow.com/questions/37906607/getters-and-setters-in-kotlin) – Edric Dec 07 '19 at 19:26

2 Answers2

1
inputFragment.arguments = intent.extras

is the Kotlin equivalent to

inputFragment.setArguments(intent.extras);

in Java.

the same holds true for accessing the value:

println(inputFragment.arguments)

is the same as

System.out.println(inputFragment.getArguments());

you can read more about the default getter and setter in the reference guide.

Simulant
  • 19,190
  • 8
  • 63
  • 98
0

This appears to be due to Java/Kotlin interop.

Kotlin docs for Calling Java from Kotlin > Getters and setters state:

Methods that follow the Java conventions for getters and setters (no-argument methods with names starting with get and single-argument methods with names starting with set) are represented as properties in Kotlin.

if (calendar.firstDayOfWeek == Calendar.SUNDAY) {  // call getFirstDayOfWeek()
    calendar.firstDayOfWeek = Calendar.MONDAY // call setFirstDayOfWeek()
}

The classes in question would originally be written in either Java or Kotlin. My guess is it's really in Java with getFoo() and setFoo() methods, just that those particular Android docs have the option to switch between view modes for the two different languages in an automated fashion, thus not accounting for this type of special case.

Which, would explain me being able to validly use .arguments in Kotlin, despite the docs showing entire getArgument() and setArgument() methods in both its Java and Kotlin views.

And would also explain me seeing entire get methods in .java files when control-clicking valid properties like .intent from my .kt files, in the IDE I was using (Android Studio).

Worth noting that the inverse (Calling Kotlin from Java > Properties) can be found here, which states:

A Kotlin property is compiled to the following Java elements:

  • a getter method, with the name calculated by prepending the get prefix
  • a setter method, with the name calculated by prepending the set prefix (only for var properties)
  • a private field, with the same name as the property name (only for properties with backing fields)

For example, var firstName: String compiles to the following Java declarations:

private String firstName;

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}
Cloud
  • 938
  • 1
  • 8
  • 24