kotlin - 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)
解决方案
您的?
代码中的值意味着那些某些参数可以为空。
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
在这里,如果它们为空lat
,lng
将被设置为。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
推荐阅读
- python - 如何在 QWebEnginePage-pyqt5 中使用 POST 方法打开 URL
- java - 背景图像会降低 recyclerview 的性能
- android - 如何使用 ToggleButton 从回收器视图适配器进行网络调用
- datatable - DataTable从聚合物中的vaadin-date-picker绘制日期范围
- dialogflow-es - 是否可以偏离对话流程并回到 DF 中的原始流程
- pandas - 如何从数据透视表中进行加权字数统计
- sql - 使用 EntityFramework 6 更新具有相关对象的对象
- r - Shiny:如何设置两个没有空间的小部件
- samsung-mobile - 错误:更新到 4.0.0.2 后无法连接到远程目标
- docker - gitlab-runner:无法连接到本地主机端口 80:连接被拒绝