kotlin - non null mark for platform types / methods

梦想与她 提交于 2019-12-24 07:18:25

问题


I often use UUID.randomUUID(). Type inferred by kotlin is UUID!. is there any way to tell kotlin that return type of this specific method is UUID and is always non null? or do i have to do everywhere UUID.randomUUID()!! or implement my own method?


回答1:


If you explicitly declare the types, it should declare them non-nullable instead of as a platform type.

val id1 = UUID.randomUUID() // UUID!
val id2: UUID = UUID.randomUUID()  // UUID

I do this with a function to make things a bit easier. By declaring the return type, it has the same effect:

fun generateUUID(): UUID = UUID.randomUUID()

Or as an extension:

fun UUID.next(): UUID = UUID.randomUUID()



回答2:


Kotlin does not force you to use !! on platform types. If the return value of the function from Java does not have nullability annotations @NotNull or @Nullable, it can be treated as either nullable or non-null:

val uuid1: UUID = UUID.randomUUID()
val uuid2: UUID? = UUID.randomUUID()

If you treat it as an non-null type but it is actually null, exception will be thrown.

Kotlin's doc:
If we choose a non-null type, the compiler will emit an assertion upon assignment. This prevents Kotlin's non-null variables from holding nulls. Assertions are also emitted when we pass platform values to Kotlin functions expecting non-null values etc. Overall, the compiler does its best to prevent nulls from propagating far through the program (although sometimes this is impossible to eliminate entirely, because of generics).



来源:https://stackoverflow.com/questions/48341965/kotlin-non-null-mark-for-platform-types-methods

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