private fun defaultOptions() {
val options = ArrayList<TextView>()
tvoptionone?.let { options.add(0, it) }
}
I am currently using the add(index, element) method in kotlin, However, I don't seem to understand what it represents in the element parameter of the add method.
These are the parameters for the add method I am trying to use
add(index, element)
it is the context object on which you've used the let function.
As you've used it with safe call operator (?.) it would only call let if object is non null.
Using ?.let ensures the lambda to be executed only when the object is non null. ?. ensures that object has to be non null and let makes that object available as it inside the lamda.
Here
tvoptionone?.let { options.add(0, it) }
it is a TextView as tvoptionone is a TextView, and it has a value same as tvoptionone.
In the below code
tvoptionone?.let { options.add(0, it) } }
it refers to tvoptionone
notice that lambda passed to let will be called only when tvoptionone is not null, so here it refers to tvoptionone and its value is not null
Questionmark after variable tvoptionone indicates that this variable can be null. If you write just:
options.add(0, tvoptionone)
and variable happens to be null then the add method will throw an error with wording like param element cannot be null or so.
Keyword let, in this particular example, is kind of a guardian against passing null into add method. If tvoptionone has some value (is not null) then it will be tvoptionone itself. Otherwise add method will not be called at all and compilation error will be avoided.
Scope functions are the ones you run on a value, and provide a function to run using that value. There's two kinds of scope functions in Kotlin - the ones where the value is passed in as a parameter (let, also etc.) and the ones where it becomes this (run, apply etc). They work the same, it just changes how you interact with the value - sometimes one is more convenient or suitable than the other
it is just the default name for the parameter passed in:
// these two are the same thing
name.let { println("Hi $it") }
name.let { it -> println("Hi $it") }
// rename it to something that reads better if you like
personData.firstName.let { name -> println("Hi $name") }
People have mentioned the null-check feature, where you can make the let block only run if the value is non-null:
name?.let { println("Hi $it, looking very not-null today") }
but another use for it is creating a temporary variable. If you have a var, it's possible the value will change while you're using it, so it's common to take a copy of it (so you know your copy won't change):
var importantNumber = 123
if (importantNumber > 100) {
// but it might have just been changed by another thread / coroutine and be < 100!
doThing(importantNumber)
}
var importantNumber = 123
val copy = importantNumber
if (copy > 100) {
// the copy can't change, so we know once we've checked it, it's fine
doThing(copy)
}
since let creates a variable to pass in as a parameter, it's basically making a copy in the same way:
var importantNumber = 123
importantNumber.let { if (it > 100) doThing(it) } // safe because 'it' won't change
and that's super important for nullable vars - if you check they're null, you need to know they'll stay null. Using ?.let guarantees that the value passed in as it will be non-null, because it's a copy that's been null-checked
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.
In one of the kotlin interviews, someone asked me the difference between it & this keywords.
I have a search on google but unable to find a proper answer for the question.
Can someone guide me what's the actual difference between these two?
I know this is very basic question, I am a novice in the kotlin.
it is only relevant inside a lambda with a single parameter. It is the default name for a single parameter and is a shorthand that allows you to omit naming the single parameter. A function that is declared this way might look like this:
(String) -> Unit
In a lambda, this is the receiver argument. It only works if the function is defined as having a receiver, like this:
String.() -> Unit
If the function declaration does not have a receiver, this has the same meaning it does outside the scope of the lambda. For an extension function, that’s the receiver of the extension function. Otherwise, it’s the class containing the function.
You need to know about Scope Functions:
The Kotlin standard library contains several functions whose sole
purpose is to execute a block of code within the context of an object.
When you call such a function on an object with a lambda expression
provided, it forms a temporary scope.
Inside this scope there is a Context object either as this or it
In Scope functions run, apply and with the scope is (temporarily) changed to the scope of the object you are calling this function on:
val str = "Hello"
str.run {
//Here this refers to str
}
In Scope functions let, also the scope is not changed (remains the same as caller scope) but your lambda will receive the context as it inside the lambda:
val str = "Hello"
str.let {
//Here it refers to str
}
You can check the links for more information.
Difference between it & this keywords can be explained by taking example of lambda method receivers (a.k.a higher order functions).
Let's say you've written a function or using a function which provides you callback as lambda method receiver. Something like this: () -> Unit
So, there are two possibilities how you want your callback to be:
Providing parameter to callback
Parameter by callback means you want to give your callback a parameter that caller can use on the time of invocation, also considered as it.
Whatever written above simply means: (Int) -> Unit. this functional method parameter can give you integer at the time of invocation.
Check out the snippet below:
fun someMethodWithCallback(callback: (Int) -> Unit) {
callback(0)
}
// On the time of consumption, the `Int` parameter by default exposed to callback as it parameter.
obj.someMethodWithCallback { it -> // Here it is the method parameter of callback that we passed, you can also rename it to any other named value
// it can be directly used as Int value if needed or you can rename it at receiver above
}
Note: You can provide multiple parameters to callback and then you won't be able to receive it, rather callback would provide you number of variables passed instead.
Providing object to callback
Another way to provide callback is by providing object itself as callback parameter. Which means that callback syntax slightly changes and gives you object itself as callback parameter this.
Whatever written above simply means: Int.() -> Unit. this functional method object can give you integer at the time of invocation.
Check out the snippet below:
fun someMethodWithCallback(callback: Int.() -> Unit) {
callback(0)
}
// On the time of consumption, the `Int` parameter by default exposed to callback as it parameter.
obj.someMethodWithCallback { this // Here this is the method object of callback that we passed, you can not rename it to anything else
// it can be used as Int value by referencing as this
}
Hope it make sense!
If this helps some one :
With scope like : run, apply, with, to call the methods of the object, we can call them directly as it has scope of the object. In another words run-block has "this" scope.
private fun methodWithRun() {
val dummy = Dummy()
dummy.run {
this.dummyFun()
this.dummyVar = "10"
}
}
While scope like : let, also, to call the methods of the object, we can call them using the "it" as it has scope of the class win which this method is written.
private fun methodWithLet() {
val dummy = Dummy()
dummy.let {
it.dummyFun()
it.dummyVar = "10";
}
}
I would like to go extreme fundamental with no fancy words. it keyword When you have one parameter you can call using it
keyword and it works so good with HOF, for instance,
private fun itKeyword(itKeyword:(String) -> Unit) {
itKeyword("")
}
fun callItFun() {
itKeyword {//it:String // this is high light over here like this
}
But if you try to do something like this:
private fun itKeyword(itKeyword:(String, Int) -> Unit) {
itKeyword("", 1)
}
fun callItFun() {
itKeyword {yourName, age -> //yourName, age is define by user
}
}
see? there is no it keyword define over here by compiler but instead we have to pass two parameters when we defined HOF but if we keep this empty, compiler will give us error Hey pass something dude, i don't what variable you are talking about there are two variables passed over here.
That means, when you have only one parameter you can call it by using it keyword.
this keyword
there are two scope or variables/properties global and local scope, when you have defined some variable as a global scope and you wanna call it in multiple methods/functions and at some place you have to use same type of another variable with the same name at local scope, in that case we will be using this keyword and why is that so?
private lateinit var mContext: Context
fun thisKeyword(mContext: Context) {
this.mContext = mContext
}
but what if we don't use this keyword and keep it like this:
private lateinit var mContext: Context
fun thisKeyword(mContext: Context) {
mContext = mContext
}
Compiler would say, mah man what have you done, didn't ring a bell in my head JK, Compiler would say, Val cannot be reassigned, wait what? we didn't init it as a val but if we see at global scope we have init it as var but guess what? compile is right. In Kotlin when pass something into functions parameter they act as a Val by default which means without this compiler was using local scope variables not global scope but when we use this keyword we tell compiler, with keyword this property over here before = is global scope this.mContext and after = is local one so this is the reason we use this keyword to refrains from variable conflict. i hope this helps, thankYou().
If you take a look at kotlin scope functions doc:
https://kotlinlang.org/docs/scope-functions.html
Some of them have "this" in their scopes and others use "it".
The difference is the following:
this: When you use scope functions that use "this", f.i. apply {} it changes the context of function's scope to the context of an object on which this function was called, e.g.:
//Outer context in outer scope
val alice = Person("Alice").apply {
//Person object's context in function's inner scope
this.age = 20 //"this" refers to the object's context
city = "London" //you can skip writing "this" because you are in the context of object
}
it: When you use functions that use "it", f.i. also {} it DOES NOT change the context of function's scope, so it remains the same as the context where the function was called, e.g.:
//Outer context in outer scope
val alice = Person("Alice").also {
//Same outer context in function's inner scope
it.age = 20 //"it" refers to the object's reference holder e.g. alice
it.city = "London" //you can not skip writing "it" because you are in outer context
}
NOTE:
The context and the scope are 2 different things.
In both cases the scope is changed so that if you declare a local variable within that scope it will not be visible from outer scope, and in 1 case the context changes and in the other one it remains the same and hence the usage of "this" and "it".
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
When using the .let { } function I noticed that when doing the following:
bucket?.assignedVariantName.let {
bucket?.determineVariant() <-- guarantee safety for bucket
}
You have to guarantee safety for a bucket in this case i.e. bucket?. or bucket!! while null safety
Since bucket is nullable, you don't need to call let on assignedVariantName, do it like this
bucket?.let {
it.determineVariant()
}
Standard function let() provides block as lambda method expression to callback on invocation. So, variable on which it's being called is passed as it in argument of block.
So, if you use it on safe call operator, it provides you non-null variable as it in callback. You can also rename it whatever you want like below :
bucket?.assignedVariantName?.let {
it.determineVariant() //<-- You can directly use it here
}
or rename it like anything:
bucket?.assignedVariantName?.let { name ->
name.determineVariant() //<-- Renaming `it` to `name`
}
Kotlin .let{} method provides null safety
bucket?.assignedVariantName?.let {
// use `it` as non-null variable
it.determineVariant()
}
You need to use it inside the let block to use it.
Because 'bucket' can be nullable variable there are different ways to make null safe calls in Kotlin, one of the standard method is using the 'let' function with safe call operator -'?'
So if you want to guarantee safety for a bucket in this case, it should be,
bucket?.let { nullSafeBucket ->
nullSafeBucket.assignedVariantName?.let { nullSafeAssignedVariantName ->
nullSafeBucket.determineVariant() -- > bucket is null safe
//assignedVariantName is as well null safe
}
}
}
Important to note - bucket!! will throw NPE if the value is null which will lead to a crash, hence it is not recommended unless 100% sure that the value is not null.
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()
}