Reputation: 24908
I want to execute a msg if the location
is null, and another msg if it is not null, so I'm trying use the elvis-operator as a?.let{} ?: run{}
statement, but the run
part is not reachable, and it tells me it is not required nor non-nullable!
The function I'm getting the error with, is:
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
)
}
)
Th getLocation
function is:
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)
}
}
}
Upvotes: 1
Views: 165
Reputation: 6569
In fun getLocation(context: Context, callback: (Location) -> Unit)
, the parameter Location
of callback
is NotNull, so it's never null, this is why location?.let
causes a warning -- it's never null so it's impossible to enter the ?: run
part of the expression.
AFAIK you want this code (parameter of callback
is made Nullable, removed unnecessary NotNull assertion, add null check instead of assertion):
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)
}
}
}
And now this code work. I've did a little refactor to make it look nicer
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)
}
Upvotes: 5