Disable not null checks in Kotlin
Asked Answered
S

2

9
class User(val name: String)

I know that in constructor will be added this check

Intrinsics.checkParameterIsNotNull(name)

To make sure that name do not store null.

Is there a way to instrument to not generate such checks? Maybe an annotation?

We need this in Spring, when map json string to a class. The validation is done by @NotNull and @Validfrom javax

class User(@field:NotNull @field:Email val name: String)

so, checks are performed immediately after object creation, but since exceptions are thrown from constructor this is not possible.

Semantic answered 19/3, 2018 at 10:31 Comment(2)
How is the value of name being set if the object gets constructed with a null name? How is the Spring version enforced to be valid? Seems like an unusual scenario.Yearly
Spring set name to null and after object creation validate the name property to be not null, if it is null it return an object with all properties that not pass validationSemantic
S
6

You can see how to do it in this post, using either a compiler flag:

-Xno-param-assertions

Or Proguard:

-assumenosideeffects class kotlin.jvm.internal.Intrinsics {
 static void checkParameterIsNotNull(java.lang.Object, java.lang.String); 
}
Sher answered 19/3, 2018 at 10:54 Comment(2)
Thanks, but we want to disable it only for some cases, not at all. Maybe an annotation.Semantic
Where to add this statement. I mean in which file?Corny
N
1

With Proguard, you can add this rule to get ride of all null checks

-assumenosideeffects class kotlin.jvm.internal.Intrinsics {
    static void checkParameterIsNotNull(java.lang.Object, java.lang.String);
}
Nodababus answered 19/3, 2018 at 10:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.