4

I'm using Kotlin for development. When I reached the official Android tutorial's fragment section, I came across the supportFragmentManager. Which is available to use as a variable in Kotlin, whereas in java we can call its equivalent method getSupportFragmentManager().

I wonder where is the supportFragmentManager variable defined as I could not see anything like a variable declaration with that name, however clicking that variable took me to the following method inside fragmentActivity.java class.

/**
 * Return the FragmentManager for interacting with fragments associated
 * with this activity.
 */
public FragmentManager getSupportFragmentManager() {
    return mFragments.getSupportFragmentManager();
}

How does this method come to be accessible as a variable in Kotlin whereas in java we've to access like a regular method? Any help would be appreciated.

spaceplane
  • 607
  • 1
  • 12
  • 27
fayis003
  • 680
  • 4
  • 10
  • 1
    Kotlin only has properties and it converts java getters and setters to properties automatically. – Arrowsome May 27 '20 at 08:04
  • 2
    Kotlin replaces getter and setter calls with a synthetic sugar, http://www.k0ma.co.za/blog/2018/11/04/JavaToKotlin-pt3/ normal variable calls getter while assigning variable (with =) calls respective setter. – Animesh Sahu May 27 '20 at 08:05
  • As usual, another good description @AnimeshSahu. – Pranav P May 27 '20 at 08:08

2 Answers2

4

Actually, in Kotlin when you call supportFragmentManager it's not variable, Any Java method contains get prefix (without argument) in the method in Kotlin it will be called like a variable without get word

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. Boolean accessor methods (where the name of the getter starts with is and the name of the setter starts with set) are represented as properties which have the same name as the getter method.

Read more about here

Công Hải
  • 4,961
  • 3
  • 14
  • 20
2

This is something like the getter and setter method in Kotlin. You don't need to describe getProperty() and setProperty() method to access/update value of property.

You can know more about how it actually works with an example from this question/answers.

I hope it will help you. Happy coding..!

Pranav P
  • 1,755
  • 19
  • 39