Why is it giving a warning? - kotlin

I replaced it with Val and the texts did not go away.
Edit: Changing it manually fixed it. But why "var" is it giving an error?
"Variable is never modified so it can be declared using 'val'"

In many languages, compile time validation yields information about the mutability of variables. Variables that do not change value during the execution of a function are invariables. In Kotlin (and some other languages) it is highly recommended to mark those invariables as such (by using the keyword val instead of var).
If you use val, then this has two consequences.
The obvious one is, that the value cannot change any longer. If you try to assign a new value later on, the compiler will yield a compile time error, and you must either assign the new value somewhere else, or change the val back to var. This ensures, that the original value is not accidentally changed.
{
val pi = 3.141d
for (...
pi = 3 // This will not compile
)
}
The less obvious effect is, that any reader of the scope will immediately see that the value will never change during the scope's existence. This is a great benefit in readability, as it signals any reader that variable changes happen elsewhere.
{
val myMessage = "..."
...
// Here I can be sure that myMessage is still "..."
}
It is therefore useful to mark invariables as val, as it helps read and understand the code and adds to safety in execution.

In Kotlin, var denotes a variable that can be reassigned different values, while val denotes a variable that cannot.
If you never reassign a var, it's better to show that you don't need this by using val instead. The compiler can do better optimizations and in particular smart casts with vals.
As a rule of thumb: if the compiler doesn't force you to use var, use val.

Related

Should I use an explicit return type for a String variable in Kotlin?

In Kotlin, We can declare a string read-only variable with type assignment and without type assignment (inferred) as below.
val variable_name = "Hello world"
or
val variable_name: String = "Hello world"
I'm trying to figure out what is the best in Kotlin and why it is the best way. Any idea?
If this is a public variable, using an explicit return type is always a good idea.
It can make the code easier to read and use. This is why your IDE probably shows the return type anyway, even when you omit it from the code. It's less important for simple properties like yours where the return type is easy to see at a glance, but when the property or method is more than a few lines it makes much more difference.
It prevents you from accidentally changing the type. With an explicit return type, if you change the contents of the property so that it doesn't actually return the correct type, you'll get an immediate compile error in that method or property. With an implicit type, if you change the contents of the method you could see cascading errors throughout your code base, making it hard to find the source of the error.
It can actually speed up your IDE! See this blog post from the JetBrains team for more information.
For private variables, explicit return types are much less important, because the above points don't generally apply.
Personally either one works and for me nothing is wrong, but I would choose the later if this is a team project, where project size increase and feature inheritance(members leaving, new hiring or worse shuffling people) is probable. Also I consider the later as more of a courtesy.
There are situations where regardless of the dogma every member follows, such as clean architecture, design-patterns or clean-coding, bloated codes or files are always expected to occur in such big projects occasionally, so the later would help anyone especially new members to easily recognize at first glance what data type they are dealing with.
Again this this is not about right or wrong, as kotlin is created to be idiomatic, I think this is Autoboxing, it was done in kotlin for codes to be shorter and cleaner as few of its many promise, but again regardless of the language, sometimes its the developer's discretion to have a readable code or not.
This also applies with function return types, I always specify my function return types just so the "new guy" or any other developer will understand my function signatures right away, saving him tons of brain cells understanding whats going on.
fun isValidEmail() : Boolean = if (condition) true else false
fun getValidatedPerson(): Person = repository.getAuthenticatedPersonbyId(id)
fun getCurrentVisibleScreen(): #Composable ()-> Unit = composables.get()
fun getCurrentContext(): Context if (isActivity) activityContext else applicationContext

How to know val's value is assigned at compile time or at runtime?

Is there any way to know Val's value is known at compile-time or at runtime? I mean can I check that at IDE or somewhere? Since after I google it, there is no article talk about it. They just point out which is known at compile and which is known at runtime, but don't mention how to know that.
As far as I know, if I assign a primitive type or String to Val, its value will be known at compile time. Instead, if I assign a function or object(the value needs to be computed or reference from another place), its value will be known at runtime.
But is there any way to verify that or to know that the value we assigned will be known at compile time or runtime(through IDE or decompile)?
Use a const val.
If you declare a val with the additional modifier const, the compiler will make sure that it is a compile-time constant.
const val myCompileTimeConstant = "Hello, World!"
https://kotlinlang.org/docs/properties.html#compile-time-constants
You can, at runtime, use reflection to check if a property was declared as const:
val isCompileTimeConstant = ::myCompileTimeConstant.isConst //true

How to disable all optimization when using COSMIC compiler?

I am using the COSMIC compiler in the STVD ide and even though optimization is turned of with -no (documentation says "-no: do not use optimizer") some lines of code get removed and cannot have a breakpoint placed upon them, nor are they to be found in the disassembly.
I tried to set -oc (leave removed instructions as comments) which resulted in not even showing the removed lines as comment.
bool foo(void)
{
uint8_t val;
if (globalvar > 5)
val = 0;
for (val = 0; val < 8; val++)
{
some code...
}
return true;
}
I do know it seems idiotic to set val to 0 prior to the for loop but lets just assume it is for some reason necessary. When I set no optimization I expect it to be not optimized but insted the val = 0; gets removed without any traces.
I am not looking for a workaround like declaring val volatile whitch solves the problem. I am rather looking for a way to prevent the optimization or at least understand/know what changes are made to my code when compiling.
It is not clear from the manual, but it seems that the -no option prevents assembly level optimisation. It seems possible that the code generator stage that runs before assembly optimisation may perform higher level optimisation such as redundant code removal.
From the manual:
-cp
disable the constant propagation optimization. By default,
when a variable is assigned with a constant, any subsequent access to that variable is replaced by the constant
itself until the variable is modified or a flow break is
encountered (function call, loop, label ...).
It seems that it is this constant propagation feature that you must explicitly disable.
It is unusual perhaps, but it appears that this compiler optimises by default, and distinguishes between compiler optimisations and assembler optimisations (performed as the compilation stage), and them makes you switch off each individual optimisation separately.
To avoid this in the code, rather than switching it off globally, you could initialise val to a non-zero value in this case:
int val = -1 ;
Then the later assignment to zero will require explicit code. This has the advantage over volatile perhaps in that it will not block optimisations when you do enable them.
I believe that this behaviour is allowed by the C language specification.
You are effectively writing the same value either once or twice to the same variable on successive lines of code. The compiler could assign this value to either a processor register or a memory location as it sees fit and knows that the value following the initial assignment in the for loop is the same as the value assigned when the if clause is actioned. As a result the language spec allows the compiler to throw the redundant code away.
The way to force the compiler to perform all read and write accesses to the variable is to use the volatile keyword. That is what it is for.

What is the difference between not-null checks in Kotlin?

There are some ways to fulfill a null-checking in Kotlin:
1.
if(myVar != null) {
foo(myVar)
}
2.
myVar?.let {
foo(it)
}
3.
myVar?.run {
foo(this)
}
What are the difference between these ways?
Are there any reasons (performance, best practice, code style etc.) why I should prefer on way over the other?
!! is to tell the compiler that I am sure the value of the variable is not null, and if it is null throw a null pointer exception (NPE) where as ?. is to tell the compiler that I am not sure if the value of the variable is null or not, if it is null do not throw any null pointer.
Another way of using a nullable property is safe call operator ?.
This calls the method if the property is not null or returns null if that property is null without throwing an NPE (null pointer exception).
nullableVariable?.someMethodCall()
All three code are behave same null check in operation-wise.
?. is used for chain operations.
bob?.department?.head?.name // if any of the properties in it is null it returns null
To perform a chain operation only for non-null values, you can use the safe call operator together with let
myVar?.let {
foo(it)
}
the above code is good for code style and performance
more details refer Null Safety
The ways 2 and 3 are more idiomatic for Kotlin. Both functions are quite similar. There is little difference with argument passing.
For example, we have a nullable variable:
var canBeNull: String? = null
When you working with T.run you work with extension function calling and you pass this in the closure.
canBeNull?.run {
println(length) // `this` could be omitted
}
When you call T.let you can use it like lambda argument it.
canBeNull?.let {
myString -> println(myString.length) // You could convert `it` to some other name
}
A good article about Kotlin standard functions.
All three are roughly equivalent.
The if case is more like most other languages, and so many developers may find it easier to read.
However, one difference is that the if case will read the value of myVar twice: once for the check, and again when passing it to foo(). That makes a difference, because if myVar is a property (i.e. something that could potentially be changed by another thread), then the compiler will warn that it could have been set to null after the check. If that's a problem (e.g. because foo() expects a non-null parameter), then you'll need to use one of the other cases.
For that reason, the let case has become fairly common practice in Kotlin. (The run case does just about the same thing, but for some reason isn't as popular for this sort of thing. I don't know why.)
Another way around it is to assign myVar to a temporary value, test that, and then use that. That's also more like other languages, but it's more verbose; many people prefer the conciseness of the let case — especially when myVar is actually a complicated expression.
The examples in your question don't show the true reason to decide.
First of all, since you're not using the return value of foo, you should use neither let nor run. Your choice is between also and apply.
Second, since you already have the result you want to null-check in a variable, the difference fades. This is a better motivating example:
complexCall(calculateArg1(), calculateArg2())?.also {
results.add(it)
}
as opposed to
val result = complexCall(calculateArg1(), calculateArg2())
if (result != null) {
results.add(result)
}
The second example declares an identifier, result, which is now available to the rest of the lexical scope, even though you're done with it in just one line.
The first example, on the other hand, keeps everything self-contained and when you go on reading the rest of the code, you are 100% confident that you don't have to keep in mind the meaning of result.
Kotlin have new features with NullPoint-Exception as Compare to Java.
Basically When we do Coding in Java , then we have to Check with !! in every Flied.
But in Kotlin, it is Easy way to Implement First
as Like,
Suppose, in Kotlin
var response:Json?=Null
response:Json?.let {
this part will handle automatic if response is Not Null....then this Block start Executing }?.run {
This is Nullable But, where we Can put Warring } So, I am Suggest you Guys to Start Work in Kotlin with this Features Provided by Kotlin.
(Flied)?.let { Not Null Value Comes Under }?.run{ Null Value Code }
This will Handle to NullPoint Exception or Protect You App for Crash
What you want to achieve
What you want to achieve is that the Kotlin compiler does a smart cast on the variable you are working with.
In all of your three examples, the compiler can do that.
Example:
if(myVar != null) {
foo(myVar) // smart cast: the compiler knows, that myVar can never be null here
}
The choice
Which one of the options to use, is really a matter of style. What you should not do is mix it up to often. Use one and stick to it.
You don't need to worry about performance since let and run are inlined (see inline function). This means that their code (body) is copied to the call site at compile time so there is no runtime overhead.

Why Kotlin uses the word "val" to stand for constant?

I really want to know why Kotlin use the word val to stand for constant?
If var means variable.val means what ? val means var + l or val is only one word for short?
In the Kotlin Documentation,we only have the following words.
Read-only local variables are declared using val keyword. Mutable
local variables are declared using var keyword.
This question is not only to make sense of the word val,but also Remind the WORD MAKER to tell us why they name the word,this is not a little thing,this will make us more comfortable to learn the new knowledge,we want to learn and make sense of everything.
For example,many people want to know why Swift use the word let or Why Objective-C use the .m filename extension?
I think the official documentation or response is really important,any guess or assuming is not really helpful,because it's not convictive,the confused will be still the confused.
I also asked this question in the official forum:
https://discuss.kotlinlang.org/t/why-kotlin-use-the-word-val-to-stand-for-constant/4491
Some references:
https://discuss.kotlinlang.org/t/change-val-to-something-else/1180/13
val means value
This is a read-only value.
var is a mutable value
const would on the other hand be not 100% correct. The value PI (3.14..) is a constant. Its value never changes. The value of x in this line val x = random.nextInt() will (hopefully) always be different, but you want the value not to be modified in the function. So the keyword val is quite appropriate.
val keyword is only one word. abbreviation for val not found anywhere. Your question explains what is val.
Read-only local variables are declared using val keyword. Mutable
local variables are declared using var keyword.
Here is a site explains why val is Read-only and not immutable.
http://blog.danlew.net/2017/05/30/mutable-vals-in-kotlin/
val does not mean immutable, val means read-only. That means that
you're not allowed to explicitly write to a val, but it doesn't
guarantee that they're immutable
https://artemzin.com/blog/kotlin-val-does-not-mean-immutable-it-just-means-readonly-yeah/
Kotlin allows you declare get() of the val which breaks immutability
of the property and leaves only read permission for external "users".
Kotlin's syntax is inspired by Scala. In Kotlin several ideas are taken from Scala besides the syntax. Kotlin also adds things on its own and does certain things very differently than Scala (i.e., no implicit conversion in Kotlin compared to Scala). Long matter short: You have to ask the Scala guys why they chose the keyword combination var and val.
val from value.
var from variable.
value - a property such as number assigned to or calculated for a variable, constant or expression(wiki)
variable - a symbolic name associated with a value and whose associated value may be changed(wiki)