Search code examples
kotlinbuilderkotlin-dslkotlin-contracts

How to write the following Kotlin contract?


The question is very simple: (using Kotlin 1.3.71)

I have the following data alike this one:

data class Location(val lat: Double, val lng: Double)

I want to achieve a type-safety with a call like so:

val loc = location {
    lat = 2.0
    lng = 2.0
}

To achieve so I built:


fun location(builder: LocationBuilder.() -> Unit): Location {
    val lb = LocationBuilder().apply(builder)
    return Location(lb.lat!!, lb.lng!!)
}

data class LocationBuilder(
    var lat: Double? = null,
    var lng: Double? = null
)

To avoid having !! operators I would like to write a contract that helps the compiler infere a smartcast that says that the attributes lat and lng are not null but I have not been able to do that successfully.

I've tried things without success and I believe it might be because I am not fully understanding the dynamics of contracts. Those are the style of:



fun LocationBuilder.buildSafely(dsl: LocationBuilder.()->Unit): LocationBuilder {
    contract {
        returnsNonNull() implies ([email protected] != null && [email protected] != null)
    }
    apply(dsl)
    if(lat == null || lng == null) throw IllegalArgumentException("Invalid args")

    return this
}

fun location(builder: LocationBuilder.()->Unit): Location {
    val configuredBuilder = LocationBuilder().buildSafely(builder)

    return Location(configuredBuilder.lat, configuredBuilder.lng)
    /* I would expect a smart cast but I am getting a compile error stating that lat and lng may still be null */
}

So the question is:

Can this be done with the current Kotlin version? If so, how?


Solution

  • This is currently not possible. A contract can't be based on the properties of the class in the contract, so when you check latitude or longitude in the contract, that's not allowed.