Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin from Java: is a field nullable or not?

Tags:

java

kotlin

When accessing Kotlin classes from Java, is it possible during runtime to tell if a particular field is nullable or not? Also, is it possible to tell if a class is a data class?

Even a guess would be sufficient for my purposes. Using reflection is also fine.

like image 613
Dmitry Ryadnenko Avatar asked Dec 12 '16 09:12

Dmitry Ryadnenko


People also ask

Is any nullable Kotlin?

Any is only a superclass of non-nullable types. This makes it possible to write code that requires a non-null instance of anything, and still benefit from the safety of the type-checker (unlike when using Java's Object ).

How do you make a field nullable in Kotlin?

However, we can make a nullable type object, by explicitly informing Kotlin that the object can be null. When using a nullable type, the Secure Access Operation ?. or Not Null Assertion !! operators have to be used to access the nullable variable. The not-null assertion operator ( !! )

How do I check if a variable is null in Kotlin?

You can use the "?. let" operator in Kotlin to check if the value of a variable is NULL. It can only be used when we are sure that we are refereeing to a non-NULL able value.

Can Java and Kotlin be used together?

Android Studio provides full support for Kotlin, enabling you to add Kotlin files to your existing project and convert Java language code to Kotlin. You can then use all of Android Studio's existing tools with your Kotlin code, including autocomplete, lint checking, refactoring, debugging, and more.


1 Answers

If you have a java.lang.reflect.Field instance for a property, you can first obtain the original Kotlin representation of the property by converting it to the kotlin.reflect.KProperty instance with kotlin.reflect.jvm.ReflectJvmMapping, and then get the type and check its nullability or anything else:

public static boolean isNullable(Field field) {
    KProperty<?> property = ReflectJvmMapping.getKotlinProperty(field);
    return property.getType().isMarkedNullable();
}
like image 101
Alexander Udalov Avatar answered Oct 02 '22 08:10

Alexander Udalov