Say I have a class like this:
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" } }
}
This class ensures that if path != null
if and only if url != null
Kotlin contracts seems the way to tell the compiler about these kinds of relations. Is the above invariant possible to model with Kotlin contracts?
My end result is to let code like the following compile:
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())
}