gpt4 book ai didi

android - 如果 null 其他不起作用

转载 作者:行者123 更新时间:2023-11-29 14:59:49 27 4
gpt4 key购买 nike

如果 location 为空,我想执行一个消息,如果不为空,我想执行另一个消息,所以我正在尝试使用 elvis-operator作为 a?.let{} ?: run{} 语句,但是 run 部分不可访问,它告诉我它不是必需的,也不是不可空的!

我遇到错误的函数是:

getLocation(
context,
{ location ->
location?.let {
msg = ("As of: ${Date(it.time)}, " +
"I am at: http://maps.google.com/?q=@" +
"${it.latitude}, ${it.longitude}, " +
"my speed is: ${it.speed}")
} ?: run { . // Getting error here
msg = "Sorry, it looks GPS is off, no location found\""
}

sendSMS(
context,
address,
msg,
subId
)
}
)

getLocation 函数是:

object UtilLocation {
private lateinit var l : Location

@SuppressLint("MissingPermission")
fun getLocation(context: Context, callback: (Location) -> Unit) {
fusedLocationClient = LocationServices.getFusedLocationProviderClient(context!!)

fusedLocationClient.lastLocation
.addOnSuccessListener { location : Location? ->
this.l = location!!
callback.invoke(this.l)
}
}
}

最佳答案

fun getLocation(context: Context, callback: (Location) -> Unit)中,callback的参数Location为NotNull,所以它永远不会为空,这就是 location?.let 导致警告的原因——它永远不会为空,所以不可能输入表达式的 ?: run 部分。

据我所知,您需要此代码(回调 的参数可空,删除不必要的 NotNull 断言,添加空检查而不是断言):

object UtilLocation {
private lateinit var l : Location

@SuppressLint("MissingPermission")
fun getLocation(context: Context, callback: (Location?) -> Unit) {
fusedLocationClient = LocationServices.getFusedLocationProviderClient(context)
fusedLocationClient.lastLocation
.addOnSuccessListener { location : Location? ->
if (location != null) this.l = location
callback.invoke(this.l)
}
}
}

现在这段代码可以工作了。我做了一些重构,让它看起来更漂亮

getLocation(context) { location ->
msg = location?.let {
"As of: ${Date(it.time)}, " +
"I am at: http://maps.google.com/?q=@" +
"${it.latitude}, ${it.longitude}, " +
"my speed is: ${it.speed}"
} ?: run {
"Sorry, it looks GPS is off, no location found\""
}

sendSMS(context, address, msg, subId)
}

关于android - 如果 null 其他不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49573760/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com