I convert a class from java to kotlin, provided that the class is working

public class CurrentActivityUtil { Activity currentActivity; public Activity getActivityInstance() { getInstrumentation().runOnMainSync(new Runnable() { public void run() { Collection<Activity> resumedActivity = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED); for (Activity act : resumedActivity) { currentActivity = act; break; } } }); return currentActivity; } } 

I convert hotkey ctrl+alt+shift+K studio offers me the following code variant:

 class CurrentActivityUtil { internal var currentActivity: Activity val activityInstance: Activity get() { getInstrumentation().runOnMainSync { val resumedActivity = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED) for (act in resumedActivity) { currentActivity = act break } } return currentActivity } } 

And immediately emphasizes internal var currentActivity: Activity - it must be initialized or be abstract, I try to make it just val currentActivity: Activity but immediately it emphasizes the line val currentActivity: Activity - val cant be reassigned.

2 answers 2

In Kotlin, a variable cannot take the value NULL, unless you have indicated this directly.

You have three options:

  1. All the same, set the variable value when it is declared.
  2. Using lateinit is, as it were, a promise that you initialize it before attempting to use it for the first time. Any NPE will be on your conscience.
  3. Define it as NULLABLE, thus: internal var currentActivity: Activity? . Question mark after class name.

Well, one more thing. val declaration means that the variable is immutable, i.e. constant and can only be read. To define a "normal" variable, use var

    I will join the answer to this earlier simply by giving a ready-made solution for your class, as I would have done:

     class CurrentActivityUtil { internal var currentActivity: Activity? = null val activityInstance: Activity? get() { getInstrumentation().runOnMainSync { val resumedActivity = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED) for (act in resumedActivity) { currentActivity = act break } } return currentActivity } } 
    • Yet for storing the activity (generally a slippery moment), or links to the lateint interface lateint looks much more harmonious, kmk. - rjhdby