懒惰初始化Kotlin类属性将无法编译

时间:2016-11-03 19:17:32

标签: kotlin

我不完全确定我认为实际上是什么问题。但我试图使用lazy作为委托,我收到编译错误

data class Geocode(var latitude: Double, var longitude: Double) : Comparable<Geocode> {


    override fun compareTo(other: Geocode): Int {
        var result = this.latitude.compareTo(other.latitude)
        if (result == 0)
            result = this.longitude.compareTo(other.longitude)
        return result
    }
}

data class HubKt(val position:Geocode) {
}

data class Example(val hubs:Collection<HubKt>) {

    val bounds:Any by lazy {
        object {
            val ne: this.hubs.map { h -> h.position }.max()
            val sw: this.hubs.map { h -> h.position }.min()
        }

    }
}

如果这是java,我希望bounds函数返回一个map:

public Map<String,Geocode> getBounds() {
        Geocode ne = geos.stream().max(Geocode::compareTo).get();
        Geocode sw = geos.stream().min(Geocode::compareTo).get();
        return ImmutableMap.of("ne",ne,"sw",sw);
}

我认为问题不是使用正确的this。我试过this@Authenticate,这是不行的。天哪,我甚至可能会让它复杂化。感谢您的见解。

2 个答案:

答案 0 :(得分:3)

根据问题中的当前代码:

data class Bounds(val ne: Geocode, val sw: Geocode)

data class Example(val hubs:Collection<HubKt>) {
    val bounds: Bounds by lazy {
        Bounds(hubs.map { it.position }.max()!!, 
               hubs.map { it.position }.min()!!)
    }
} 

否则,在您的回答中,您无法访问通过对象表达式创建的ne匿名后代中的swAny。您需要一个类型化的响应,例如Bounds类或Map(这将是icky)。而且在你的版本中,它们可能为空。如果您知道列表中至少有一个值,则可以使用!!断言您知道maxmin的结果不会为空。

您可以在没有地图创建的副本的情况下执行此更改:

data class Example(val hubs:Collection<HubKt>) {
    val bounds: Bounds by lazy {
        Bounds(hubs.maxBy { it.position }!!.position, 
               hubs.minBy { it.position }!!.position)
    }
}    

或者,如果您希望空值作为可能的边界,请使用?.安全运算符而不是!!.,并将Bounds类更改为允许null

data class Bounds(val ne: Geocode?, val sw: Geocode?)

data class Example(val hubs:Collection<HubKt>) {
    val bounds by lazy {
        Bounds(hubs.maxBy { it.position }?.position, 
               hubs.minBy { it.position }?.position)
    }
}

请注意,在上一个示例中,我从val bounds: Bounds中删除了类型,因为它是可选的,类型推断会很好地解决它。

答案 1 :(得分:-1)

好的,我解决了这个问题:2折

语法错误为“未知符号”?我需要=而不是:(DOH!)

  val bounds:Any by lazy {
        object {
            val ne = hubs.map { h -> h.position }.max()
            val sw = hubs.map { h -> h.position }.min()
        }

    }

Lombok:position中的Hub让龙目岛产生了它的吸气剂:

@Getter
@Setter
private Geocode position = new Geocode(50.0,50.0);

更改为:

@Setter
private Geocode position = new Geocode(50.0,50.0);

public Geocode getPosition() {
    return position;
}

最终这是一个整合问题。 叹息

相关问题