Reputation:
i want solve this problem.
this java code
Activity activity = getActivity();
if (null != activity) {
activity.finish();
}
How I can use this code using kotlin?
val activity: Activity = getActivity()
activity.finish()
when I convert this code to kotlin
like above code.
getActivity()
-> get error.
Anyone can help?
Upvotes: 1
Views: 12913
Reputation: 3187
I had the same question, when I was new to Kotlin.
In Java:
Activity a = getActivity();
if (null != a) {
a.finish();
}
In Kotlin:
let a = activity
a?.finish()
or just
activity?.finish()
It is clarified in Calling Java code from Kotlin:
Getters and Setters
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 withset
) are represented as properties in Kotlin. ... [Emphasis added]
Accordingly, Java method getActivity()
will be just a property activity
in Kotlin.
In addition, the null-check if (null != a) { ... }
will be just a?
, which Gregory's answer has clarified.
Upvotes: 3
Reputation: 176
Getting activity from a fragment in Kotlin is optional (might be null) so the type must be Activity?
then you have to safecall it like activity?.finish()
and it won't crash with an NPE if activity is null.
Also, you can use property syntax and just call activity instead of getActivity().
https://kotlinlang.org/docs/reference/null-safety.html
Upvotes: 3