This question already has answers here:
What's the difference between !! and ? in Kotlin?
(6 answers)
Closed 3 years ago.
I am a bit confused about the usage of ? and !! in the following instance.
lat = mLastLocation?.latitude.toString()
longi = mLastLocation!!.longitude.toString()
Which null-safety operator should I be using?
TL;DR:
?. operator is safe. Use it when you are unsure about the chain nullability.
!!. operator is meant to be used only when you are sure that the previous chain operation result is not null. Otherwise, crash.
if mLastLocation is never null, feel safe about using !!. (And about rethinking a little bit your code), otherwise, use ?.
Introduction
You have hit one of the best (and most useful) points while coding in Kotlin.
here which null safety operator I should use?
It depends on the behavior you want to achieve.
In Kotlin, you have to be very specific about what you want to do with null values, because the language is designed to be null-safe out of the box.
Of course, targeting the JVM brings many challenges to a programming language. The eventuality of having null values is one of these, and Kotlin, as we'll see, handles this in a really smart manner.
Purpose
We could explain the full theory behind those two operators, but I believe an example is really all you need.
Suppose you have a class, called Location, which we will declare in a nullable variable.
In Kotlin, this is represented as val location: Location?
Let's also say Location class has a property called lat, which is a nullable String, and a lon non-nullable String.
data class User(val lat: String?, val lon: String)
Operator ?.
Kotlin Safe Call Operator Docs
This operator is the safe call operator.
If you use it in a call chain, it is checking that your code chain goes onto the next element just if the previous element is not null. Otherwise, null is retuned from the statement.
val location: Location? = getLocation()
println(location.lat) // Compile-time error.
println(location?.lat) // Works fine.
This happens because in the first case, the object before ?. is nullable, thus the Kotlin Compiler infers that accessing a nullable property can lead to NPEs.
location could be null or not-null.We just don't know what it will be, and the Kotlin environment strictly makes sure that you are handling the eventuality of that value being null, as the type of our references variable is defined as nullable.
However, a certain variable being null is something you developer may not know. Sometimes it is not even up to you to receive a null or non-null value.
In this case you can safely stick with ?, knowing that this operator is your friend if you are unsure about whether what you're referencing will be null.
val location: Location = getSafeLocation()
val nullableLocation: Location? = getLocation()
// Fine, may print "null" or the value, if present.
// println accepts nullable values
println(location.lar)
// 100% sure it'll print the corrisponding String value
println(location.lon)
// May print "null", "null", or the lat String value.
// The first "null" is because the ? operator will check if
// nullableLocation is null. If it is, it stops the execution
// chain and returns null. Otherwise, it assumes nullableLocation is safe
// and goes on.
//
// The second "null" is because the value itself of lat
// is declared as String? and Kotlin knows it may be null.
// If println() did not accept null values, this call would fail,
// but instead it prints "null" in case lat is indeed null.
println(nullableLocation?.lat)
// Since lat was the last element of the chain, it is not
// delivered as the parameter type anymore, and thus if we
// want to read a property from it we have to ensure that it isn't null.
println(nullableLocation?.lat?.length)
// This, as you may guess, returns wither null in case nullableLocation is null,
// otherwise 100% sure it will print lon value, since it is not a String? but a String.
println(nullableLocation?.lon)
Operator !!.
Kotlin Double-Bang Operator Docs
This is the dreaded double-bang operator.
Talking about syntax, it is very similar to ?., since it is used in the same place.
To describe it in a really simple way: if anything before the call is null, your code will crash. Instantly. Without warnings.
With !!. you're explicitly saying that
Kotlin has to ignore any type nullability marker and to perform the operation you intend, even though it enters in a kind of danger zone.
This is known as a force, because you're forcing the Kotlin environment to believe that the previous statement is not null.
This operator best use case is when porting another library to Kotlin, or while handling API RESTful responses, situations where null values may come in, but because of environment/platform reasons, you know that some value can not be null. This helps you bringing type safety in the Kotlin world in the first place, if used properly.
But for mainstream software, this feature is meant for a really specific and narrow usage: If you are 100% sure that the previous call is not null, go ahead.
val location: Location? = getLocation()
println(location!!.lon)
The previous code may crash if location is
Which one to use
Both operators are type-transforming. They both turn nullable values into non-nullable ones. The way the do it is the changing factor.
As a general rule, if you're sure the value you are targeting is not null, use !!., otherwise stick with ?.
if you define a variable as
var myFirstVar:String? = null
this means that "myFirstVar" can have a null value and when you use "myFirstVar" you should indicate whether or not it has a null value
myFirstVar!!.toString
in here you're saying that you're 100% that myFirstVar will not be null (maybe you've given it a value before calling it)
but if you use ?
myFirstVar?.toString
you're indicating that myFirstVar might have a null value, the ? will chick if myFirstVar is null or not, if it is then it will not convert it to string (the application will not crash) and if it wasn't then it will convert it to string, it is a safety check to reduce the null crashes.
If a variable is declared as nullable type, you have two options when using it.
Let's take this for example:
private var myButton: Button? = null
So you have two option for the myButton. You can evaluate it, or keep it as it is. But the program on the run doesn't know what you have done with the variable before. So, in order to be safe Kotlin language provides you with ? and !! operators. One is for the safety of program, so it won't crash and cause a KNPE:
myButton?.setOnClickListener{
}
If the button is null, the app won't crash. Now, if you are 100% sure that you have evaluated the Button with a value different from null, you can use !!:
myButton!!.setOnClickListener{
}
In this case, if you run the program and the myButton is null, you will have a crash.
Null Safety Myth
However, this is not a null safety case (I guess). What people mean by null safety in Kotlin is exactly this:
private val myButton: Button = someButtonInitialization()
If you evaluate it to null, the compiler would yell at you because Button is a non nullable type. Otherwise it would be Button?.
This is null safety IMO, and not !! or ?.
Special case: You can have:
private lateinit var myButton: Button
If you never evaluate the myButton you will never have KNPE, but an UninitializedPropertyException which has nothing to do with Null threat or null safety.
Let's have an example
var a: String? = "Hello world!"
fun test1() {
a?.trim()
}
fun test2() {
a!!.trim()
}
The first decompiled function is:
public static final void test1() {
String var10000 = a;
if (var10000 != null) {
String var0 = var10000;
StringsKt.trim((CharSequence)var0).toString();
}
}
The second decompiled function is:
public static final void test2() {
String var10000 = a;
if (var10000 == null) {
Intrinsics.throwNpe();
}
String var0 = var10000;
StringsKt.trim((CharSequence)var0).toString();
}
Where Intrinsics.throwNpe(); is defined as:
public static void throwNpe() {
throw sanitizeStackTrace(new KotlinNullPointerException());
}
So a?.trim() will do nothing if var a was null
So a!!.trim() will throw an exception if var a was null
Related
This question already has answers here:
Smart cast to 'Type' is impossible, because 'variable' is a mutable property that could have been changed by this time
(12 answers)
Closed 1 year ago.
I am studying Android and I am also studying Kotlin.
While writing Android code, I was curious about using it in a let function.
MainActivity.kt
class MainActivity : AppCompatActivity() {
private var curFrag: Fragment? = null
curFrag = fm.primaryNavigationFragment
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// curFrag?.let { transaction.hide(curFrag) } // error.
curFrag?.let { transaction.hide(it) }
}
}
ERROR
Smart cast to 'Fragment' is impossible, because 'curFrag' is a mutable property that could have been changed by this time
In the lambda expression of let(), T is curFrag and the type is Fragment? is.
And T(curFrag) can be replaced by it.
But the moment I used curFrag instead of it, the IDE displayed an error message.
Later, when I checked the type of it, it was Fragment? It was not a Fragment type.
Honestly, I don't understand well.
I don't know why it is automatically smart cast and should only be used for immutable variables.
Kotlin is a null safe language, it tries to eliminate every possible null references from the code. You can perform a nullability check on the variable and then can use it like this
if(curfrag != null) { transaction.hide(curFrag)
This too will only work if variable curfrag is immutable (that means a local variable which is not modified between the check and the usage or a member val which has a backing field and is not overridable), because otherwise it might happen that curfrag changes to null after the check from some other thread.
But Safe calls ?. with let always gives us non nullable result, what Safe calls operator ?. does is, it only performs any operation following it, only if the variable is not-null otherwise it returns null.
It works with all mutable types or member var, It check for the null once and then provides the result. If value is non null it performs the defined operation otherwise skips it. it refers to the copy of that non-null value.
So when you do this
curFrag?.let { transaction.hide(curFrag) }
curFrag can be null as you are directly passing a nullable value.
But in this case
curFrag?.let { transaction.hide(it) }
it only passes value if it's a non-null value.
The let function basically creates a new variable with the same value as whatever you called it on, so it is not really smart-casting the original property.
If you use ?.let, let isn't even called if the value was null. The safe call means the receiver let is being called on is not a nullable value to begin with because otherwise let isn't called at all. The it inside let is just a reference to what it was called on.
Effectively, though it is conceptually similar to smart-casting. There is not really a way to write equivalent Kotlin code that does what ?.let is doing because the ?. safe call is a special operator that has no expanded form.
I have to following variable declaration:
var baseItemList: MutableList<BaseDataItem>? = null
when writing the line:
baseDataItemsList?.get(position).getObjectTypeNum()
I'm getting an error saying that:
Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type BaseDataItem?
but, get method doesn't return a BaseDataItem?, only a BaseDataItem since the BaseDataItem inside the brackets is without a question mark.
Can someone explain me this error, and why i have to add this question mark?
Looking at this code:
baseDataItemsList?.get(position)?.getObjectTypeNum()
The call ?.get(position) returns the position if baseDataItemsList is not null, but otherwise returns null. So even though baseDataItemsList.get() would return a non-nullable BaseDataItem (only possible to call if baseDataItemsList is not nullable), the null-safe baseDataItemsList?.get() call returns a nullable BaseDataItem?, where the null condition indicates that baseDataItemsList is null. So you must use ?.getObjectTypeNum() to account for this.
Side note: in my opinion combining var with a mutable collection is often a code smell, because you're making something mutable in two different ways, which makes it more error-prone to work with.
Make use of Kotlins scope functions, for example the let scope to avoid that warning:
baseDataItemsList?.let { baseDataItemList ->
baseDataItemList.get(position).getObjectTypeNum()
}
That way you assert that baseDataItemList cannot be null inside the let scope. If you want to read more about that topic, take a look into the documentation
I must be doing something wrong with Kotlin implementation of view models
I have a view model that has a function to retrieve youtube video id from url.
fun getYoutubeVideoId(url: String): String?{
return "([a-zA-Z0-9_-]{11})".toRegex().find(url)?.value
}
I feel like I'm always in catch 22 because I use this function in a fragment inside with LiveData observable, which forces me to to ? on objects, which then forces me to have return type with ?, which then tirggers if statements to check if objects aren't null.
Here is the vm var
val streamUrl= mainState.getOrNull { it?.account?.streamUrl ?: 0}.distinctUntilChanged()
Here is my shortened observable
streamUrl.observe{
playVideo(getYoutubeVideoId(it))
}
The error from above statement is that it
Requires a String and I'm passing Any
Return should be String and its String?
I'm running around to make sure the types match and its always something not matching or being right. I think I could setup another streamUrl variable under the viewModel besides the observable, but I feel like I should be able to just do it of a single variable.
I hope this makes sense.
So the first thing to embrace with kotlin is: Null Safety.
Null Safety does not mean that you do not get nulls.
It means, that if something is possibly null, the compiler forces you to think about it and handle it at a point that makes sense. If you don't, you potentially get the notorious NullPointerException at an unexpected and possibly ugly point of execution.
So, to eliminate the ? think about where you want to handle the possibility of it being null -> check it -> handle it in an elegant way, and then safely pass the checked result without a ? to the rest of your code.
I have pretty common piece of kotlin code here:
fusedLocationProviderClient.lastLocation.addOnSuccessListener { location: Location? ->
val geoCoder = Geocoder(this, Locale.getDefault())
val addr = geoCoder.getFromLocation(location.latitude, location.longitude, 1)
Toast.makeText(this, "Got location info", Toast.LENGTH_SHORT).show()
locationText.text = addr.get(0).toString()
}.addOnFailureListener { exception: Exception ->
locationText.text = exception.message
}
Since the location value from the callback can be null in certain cases we have to define it as a nullable type like so location: Location?. The problem arises when I want to use the latitude and longitude attributes from the location object like location.longitude. The compiler gives the following error:
Only safe (?.) or non-null asserted calls are allowed on nullable reciever of type Locaion?
Now I know doing location!!.latitude is a dangerous thing because it claims the value to not be null. And using location?.latitude gives me a type mismatch Required: Double Found: Double?
I've seen this happening many times while making async calls. My question is what is the official "kotin" way to handle situations like these?
Kotlin, unlike Java and many other languages, requires that you explicitly identify a nullable value as nullable or it will throw up a compiler error (as you've discovered). This is done to prevent the dreaded NullPointerException, an effect of the so-called billion dollar mistake (programmers the world over forgetting to check for null before assuming a variable's value is not null, and causing a NPE).
There are three ways to go about handling what you're asking about in Kotlin, and it boils down to a stylistic preference on your part plus a bit about how much code is conditioned upon the null/non-null status of the value. The methods all incorporate a null check.
For purposes of this answer, I'll assume if the latitude property is null, you want to throw an error. But one great thing about explicit nullability in Kotlin is it forces you to think about how you actually want to handle null values (is it an error that halts your code? do you plug in a default value and continue your code? etc.)
First, you can use the traditional if/else. For personal aesthetic reasons, I tend not to use this in Kotlin. I just enjoy using the other methods because they're "new" to me, coming from C-like languages, where if/else is old hat.
val myVal: Location? = someValue
if(myVal == null) {
throw IllegalStateException("myVal is null")
} else {
/* handle the non-null case(s) */
}
Second, you can use one of the Kotlin scoping functions (they are all used in subtly different ways but are interchangeable for the purposes of your question).
myValue.let tells Kotlin to stick myValue into the following code block but renamed to it. But myValue?.let tells Kotlin to do this only if myValue is non-null. If myValue is null, the block of code following let will not execute. If you put a ?: and some code after the block of code, that will be run if myValue is null:
val myVal: Location? = someValue
myVal?.let { location ->
/* handle the non-null case */
} ?: throw IllegalStateException("myVal is null")
In the above, throw ... only executes if myVal is null. If myVal is non-null, it will not throw.
The third option is similar to the second:
val myVal: Location? = someValue
myVal ?: throw IllegalStateException("myVal is null")
/* now handle the non-null case */
Remember the ?: from above? That's it again, and it operates the same way: if myVal is null, it will execute what comes to the right of it. In this case, a throw. If this were in a function, you could also do myVal ?: return someDefaultValue for example.
It operates as a type guard and ensures that for any subsequent code, myVal cannot be null (because myVal is immutable and we've now determined it's not null).
For nullable variable you need to check first variable is not null.
You can do using below methods:
if(location != null){
val latitude = location.latitude
}
or
location?.let{
val latitude = it.latitude // location can be replace with **it**
}
What's an idiomatic way to do code this in Kotlin?
private var someVar: SomeClass? = null
private fun getSomeVar(): SomeClass {
if (someVar == null) {
someVar = getDefaultSomeVar()
}
return someVar
}
Android Studio warns me about the return type. In Java this code is, however, proper and idiomatic. I mean, instead of changing the return type to SomeClass? maybe there's still a better way?
Actually, getSomeVar() can never return null
The compiler complains because, theoretically, a different thread could change someVar in between the assignment and the return statement.
The idiomatic solution here would be to use property delegation:
private val someVar: SomeClass by lazy { getDefaultSomeVar() }
This initializes the property when it is first accessed in a thread safe manner. Also note that it is now a non-nullable val, instead of a nullable var, which makes it generally easier to work with.
You do lose the ability to modify it later on. If it needs to be mutable you currently have to make that yourself. For an example implementation see this SO question: Kotlin lazy default property
The following two solutions take the method in the question (the 'java way') for granted and just show a way to prevent the compiler warning. However, in your situation these are not advised as they both have drawbacks over the lazy initialized property:
1) Introduce a local variable. This variable is safe from being mutated by other threads and allows the compiler to do a Smart Cast:
private fun getSomeVar(): SomeClass {
var value = someVar
if(value == null) {
value = getDefaultSomeVar()
someVar = value
}
return value
}
The method itself is however still not thread safe. In a multithreaded environment, getDefaultSomeVar() could be called multiple times and it is not guaranteed that the returned value of this method is equal to someVar.
2) Use !!: the double bang operator. This converts a nullable type to non-nullable. But now you lose the protection and null safety that the kotlin compiler enforces on you.
return someVar!!
As the documentation puts it: 'If you want an NPE, you can have it'
You can write:
return someVar!!
this will return a non-null value, however if it's null it will throw an NPE.
It could be shorter and without any warnings
private fun getSomeVar(): SomeClass {
return someVar?:getDefaultSomeVar()
}