Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin null from Java

Tags:

java

kotlin

When I am converting Java code from a library to Kotlin I see if null checks in the Java code and wonder how best to convert this.

Do I still need the if null check in Kotlin because I cant control if Java will make the object null?

Lets say I have a CameraDevice which could come back null from Java

Should I define this like this..

private lateinit var mCameraDevice: CameraDevice

and then no null check is needed or like this..

private var mCameraDevice: CameraDevice? = null

and then keep the null check

if (mCameraDevice != null) { // do something }

Nullability in Kotlin confuses me because I feel like I shouldn't have to deal with the null and should use option one, but basically every library I use is Java so I have to deal with nulls and go with option two

like image 434
Pagrate Avatar asked Nov 20 '25 05:11

Pagrate


2 Answers

If you're not sure, you should better use the nullable types, because it's always possible that the legacy Java code returnes null. This version is safest. If otherwise you know that null is impossible, use the non-nullable type.

As written in the docs:

Any reference in Java may be null, which makes Kotlin's requirements of strict null-safety impractical for objects coming from Java. Types of Java declarations are treated specially in Kotlin and called platform types. Null-checks are relaxed for such types, so that safety guarantees for them are the same as in Java.

If you work with Java returned values, which you think will never be null, are going to cause NullpointerExceptions at runtime if you work with them as not nullable types.

Java:

public class Nullable {

    public String get(){
        return null;
    }
}

Kotlin:

Nullable().get().length //-> NPE
like image 57
s1m0nw1 Avatar answered Nov 22 '25 17:11

s1m0nw1


if (mCameraDevice != null) { // do something }

What are you going to do in the else case? If the answer is "throw an exception", just use a non-nullable type and Kotlin will effectively do it for you; otherwise a nullable type is reasonable.

Also, if mCameraDevice is a var, inside // do something Kotlin can't assume it's non-null: something could change it after the check! A common idiom is

mCameraDevice?.let { mCameraDevice -> // do something }
like image 40
Alexey Romanov Avatar answered Nov 22 '25 17:11

Alexey Romanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!