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

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)

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

What is this Kotlin type: (String..String?)

IntelliJ is showing me context hints that my variables are of type (String..String?). I cannot find any mention of it on the internet, what is this type?
(String..String?) represents a flexible type with lower bound String and upperbound String? (nullable string). This is not valid Kotlin code (it's not denotable) but it is used in the compiler internals and thus in IntelliJ's hints sometimes.
(On the JVM we often see platform types using ! as in String!, which are a more specific case of flexible types)
It's Kotlin's way of saying it doesn't know whether the String type declared for payload.email is nullable or not (for instance if this is declared in Java, which doesn't distinguish those), and yet it doesn't want to enforce either of those, for convenience (hence "flexible").
As the name suggests, flexible types are flexible — a value of type (L..U) can be used in any context, where one of the possible types between L and U is needed
This means that even though the actual type of the value is "somewhere between String and String?", values of this type can be used even in places expecting String, even though the real type of that value may be String? and thus the value could be null.
This is useful because assuming it is String would mean that null checks would be marked as redundant, and assuming it is String? would force the developer to write null checks everywhere, even though they might know that this particular Java method cannot return null.
In general, it's a good practice to explicitly declare the type of a variable that you get from Java, to avoid the propagation of the platform type and the uncertainty (and unsafety) that comes with it:
val email: String = payload.email // if you know it cannot be null
val email: String? = payload.email // if you don't know

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

Why is it giving a warning?

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.

Kotlin [1..n] constructor parameter

Is there a way to enforce 1..* parameters in Kotlin that will still allow the spread operator?
I've tried:
class Permission(
// 1..n compliance
accessiblePage: Webpage,
vararg accessiblePages: Webpage
) {
And that does enforce 1..*, but it also means that Permission(*pages) won't work, so that's a pretty awkward interface.
Is there an easy way to enforce 1..* without a runtime constructor error?
There is, unfortunately, no way to check this in Kotlin at compile time aside from the way you mentioned. Since vararg parameters are really just syntactic sugar for an array, your code is essentially
class Permission (
accessiblePage: Webpage,
accessiblePages: Array<Webpage>
)
So the question then becomes "Can you ensure that an array has at least one element in it at compile time?" For most languages, that's a clear no, although the Kotlin team did at one point experiment with it:
[C]urrently, Kotlin compiler doesn't collect static information about
collections size. FYI, at some point Kotlin team tried to collect such
information and use it for warnings about possible
IndexOutOfBoundException and stuff like that, but it was found that
there were a very little demand on such diagnostics in real-life
projects, so, given complexity of such analysis, it was abandoned[.]
(https://github.com/Kotlin/KEEP/issues/139#issuecomment-405551324)
It's possible that this metadata will be added at some point, but you shouldn't expect it soon.
That said, you could always combine a runtime check in the case of an Array with an overloaded signature in the case of varargs. This would mean that your vararg example would work the same, but passing an array to the function would subject it to a runtime check (you'd also not have to use the spread operator anymore):
class Permission (
accessiblePage: Webpage
vararg accessiblePages: Webpage
) {
constructor(accessiblePages: Array<Webpage>) {
require(accessiblePages.isNotEmpty()) {
"Must have at least one accessible page."
}
}
}
called like
val permission1 = Permission(Webpage(), Webpage())
val permission2 = Permission() // Would fail at compile time
val pages = arrayOf()
val permission3 = Permission(pages) // Would fail at runtime. Note also the lack of the spread operator.