Is NotNull needed on Kotlin?

假如想象 提交于 2020-05-27 05:34:27

问题


I have a class:

class User(

    var name: String

)

And a mapped post request:

@PostMapping("/user")
fun test(@Valid @RequestBody user: User) {
    //...
}

What if a client will send a JSON of a user with name: null? Will it be rejected by the MVC Validator or an exception will be throwed? Should I annotate name with @NotNull? Unfortunately, I cannot check that because only can write tests (it is not available to create User(null)).


回答1:


You can avoid using @NotNull, as it'll never get triggered for non-nullable property (bean validation only kicks in after Jackson deserializes the JSON - which is where this will fail).

Assuming you're using jackson-module-kotlin, then you should get an exception with MissingKotlinParameterException as the root cause, which you can then handle in a @ControllerAdvice. In your advice you can handle normal bean validation exceptions (e.g. ConstraintViolationExceptioncaused by @Size) and missing non-null constructor params (MissingKotlinParameterException) and return an API response indicating the fields in error.

The only caveat with this is that the jackson-kotlin-module fails on the first missing property, unlike bean validation in Java, which will return all violations.




回答2:


Since name is a not-null parameter of User, it cannot accept nulls, ever.

To guarantee that Kotlin compiler:

  • inserts a null check inside the User constructor which throws an exception if some Java code tries to pass a null.

  • annotates name with@NotNull in order to stay consistent with Java APIs

  • does not add any @NotNull annotation since there isn't one which everybody agrees on :(

Here are the corresponding docs

Update

I have rechecked it, and Kotlin compiler v1.0.6 does insert @Nullable and @NotNull from org.jetbrains.annotations. I have updated the answer accordingly.




回答3:


As I tested, @NotNull doesn't affect on the MVC validation at all. You will only receive a WARN message in console which is normal:

Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Instantiation of...



来源:https://stackoverflow.com/questions/41993706/is-notnull-needed-on-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!