假设我有这样的课程:
data class URLAndPath(
val baseUrl: URL,
val path: String?
) {
val url get(): URL? =
try { path?.let { URL(baseUrl, it) } }
catch(_: Exception) { null }
init { require(path == null || url != null) { "Invalid URL $baseUrl$path" } }
}
此类确保path != null
当且仅当url != null
Kotlin 契约似乎是告诉编译器这些关系的一种方式。上述不变量是否可以用 Kotlin 合约建模?
我的最终结果是让如下代码编译:
val x = URLAndPath(URL("http://example.org/"), "index.html")
if(x.path != null) {
// currently: Error: Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type URL?
println(x.url.toURI())
}