如何撰写以下Kotlin合同?

问题描述 投票:0回答:1

问题很简单:(使用Kotlin 1.3.71]

我有以下类似数据:

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

我想通过这样的调用来实现类型安全:

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

为了达到目的,我建立了:


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
)

[为了避免使用!!运算符,我想写一个合同来帮助编译器推断一个智能广播,该广播说latlng属性不为null,但我无法成功做到这一点。 >

我尝试过没有成功的事情,我相信这可能是因为我没有完全了解合同的动态。这些是以下样式:



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 */
}

所以问题是:

可以使用当前的Kotlin版本完成此操作吗?如果是这样,如何?

这个问题非常简单:(使用Kotlin 1.3.71)我有以下类似数据:数据类Location(val lat:Double,val lng:Double)我想通过调用来实现类型安全...

kotlin builder kotlin-dsl kotlin-contracts
1个回答
0
投票

目前无法实现。合同不能基于合同中类的属性,因此,当您在合同中选中latitudelongitude时,这是不允许的。

© www.soinside.com 2019 - 2024. All rights reserved.