首页 > 解决方案 > Kotlin 转换双倍?翻倍

问题描述

我正在使用 Mapbox 开发映射应用程序。我使用的方法使用 Point(Double, Double) Getting Type Mismatch Required: Double Found: Double?

        val lat = locationComponent.lastKnownLocation?.latitude?.toDouble()
        val lng = locationComponent.lastKnownLocation?.latitude?.toDouble()
        origin = Point.fromLngLat(lat, lng)

标签: kotlindouble

解决方案


您的?代码中的值意味着那些某些参数可以为空。

locationComponent.lastKnownLocation?.latitude?.toDouble()

locationComponent.lastKnownLocation?意味着lastKnownLocation可以为null,因此latitude可以为null(纬度也可以为null,我不知道,因为我看不到模型)。

Point.fromLngLat(lat, lng)不接受空值,这意味着你需要在这里小心。

您可以通过检查代码来解决这个问题,看看是否lastKnownLocation真的可以为空,或者它只是一个未注释的 java 参数,所以编译器不知道如何处理它,所以它可以安全地播放。

在那种特殊情况下(当您知道它不能为空时),您可以使用!!将该值声明为非空(但如果您错了,这将引发 NPE)。

您还可以尝试通过提供默认值来降低风险,但是,您如何处理该默认值?你把它分配到世界的哪个地方?也许您还有其他有意义的位置组件,例如居住国的中部等(这完全取决于您的代码的其余部分)。

val lat = locationComponent.lastKnownLocation?.latitude?.toDouble() ?: 0.0 
val lng = locationComponent.lastKnownLocation?.longitude?.toDouble() ?: 0.0 

在这里,如果它们为空latlng将被设置为。0.0

但是根据您的情况,当您没有价值时,您实际上可能不想拨打电话。因此,您可以尝试事先检查它们是否为空。

val lat = locationComponent.lastKnownLocation?.latitude?.toDouble()
val lng = locationComponent.lastKnownLocation?.longitude?.toDouble()

if(lat != null && lng != null) origin = Point.fromLngLat(lat, lng)

但在这种情况下,您的原点未设置。但是,如果这些值真的可以为空,那么也许不设置该原点是有意义的。

我强烈建议您阅读以下内容:Kotlin 中的 Null Safety


推荐阅读