在编写验证函数时,这些验证函数通常会检查可空性。即使在调用这些函数之后,对象成员可以像不可为空一样安全地使用,但 Kotlin 编译器合约不允许指定此行为。
例如:
data class EmployeeDto(
val name: String?,
val longitude: String?,
val latitude: String?
) {
@ExperimentalContracts
fun validate() {
//contract { returns() implies (this.name != null && this.longitude != null && this.latitude != null) }
// Error in contract description: only references to parameters are allowed in contract description
if (name.isNullOrEmpty())
throw RequiredValueNotSetException("Name was set to \"$name\" but can not be null or empty")
if (longitude.isNullOrEmpty())
throw RequiredValueNotSetException("Longitude was set to \"$longitude\" but can not be null or empty")
if (latitude.isNullOrEmpty())
throw RequiredValueNotSetException("Latitude was set to \"$latitude\" but can not be null or empty")
}
这种约束背后的基本原理是什么,或者这是计划在未来添加的功能?