kotlin - 平台类型/方法的非空标记
kotlin - non null mark for platform types / methods
我经常用UUID.randomUUID()
。 kotlin 推断的类型是 UUID!
。有什么方法可以告诉 kotlin 这个特定方法的 return 类型是 UUID
并且总是非空的?还是我必须到处做 UUID.randomUUID()!!
或实现我自己的方法?
Kotlin 不会强制您在平台类型上使用 !!
。如果来自 Java 的函数的 return 值没有可空性注释 @NotNull
或 @Nullable
,则可以将其视为可空或非空:
val uuid1: UUID = UUID.randomUUID()
val uuid2: UUID? = UUID.randomUUID()
如果你把它当作一个非空类型,但它实际上是空的,就会抛出异常。
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).
如果您显式声明类型,则应将它们声明为不可空的,而不是声明为平台类型。
val id1 = UUID.randomUUID() // UUID!
val id2: UUID = UUID.randomUUID() // UUID
我用一个函数来做这件事,让事情变得更容易一些。通过声明 return 类型,它具有相同的效果:
fun generateUUID(): UUID = UUID.randomUUID()
或作为扩展:
fun UUID.next(): UUID = UUID.randomUUID()
我经常用UUID.randomUUID()
。 kotlin 推断的类型是 UUID!
。有什么方法可以告诉 kotlin 这个特定方法的 return 类型是 UUID
并且总是非空的?还是我必须到处做 UUID.randomUUID()!!
或实现我自己的方法?
Kotlin 不会强制您在平台类型上使用 !!
。如果来自 Java 的函数的 return 值没有可空性注释 @NotNull
或 @Nullable
,则可以将其视为可空或非空:
val uuid1: UUID = UUID.randomUUID()
val uuid2: UUID? = UUID.randomUUID()
如果你把它当作一个非空类型,但它实际上是空的,就会抛出异常。
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).
如果您显式声明类型,则应将它们声明为不可空的,而不是声明为平台类型。
val id1 = UUID.randomUUID() // UUID!
val id2: UUID = UUID.randomUUID() // UUID
我用一个函数来做这件事,让事情变得更容易一些。通过声明 return 类型,它具有相同的效果:
fun generateUUID(): UUID = UUID.randomUUID()
或作为扩展:
fun UUID.next(): UUID = UUID.randomUUID()