https://kotlinlang.org logo
#announcements
Title
# announcements
l

Leandro Cavalheiro

11/10/2017, 12:11 PM
Ok..but why always uses VAL in examples?
k

karelpeeters

11/10/2017, 12:13 PM
If you don't need a variable to be mutable it's a good idea to make it immutable because you avoid a bunch of possible bugs that way.
It also expresses your intent more clearly, when you declare the variable you immediately say that it will never change.
l

Leandro Cavalheiro

11/10/2017, 12:20 PM
But, I can't see usability in the class, why normally an class normally an table ... and make insert / update of data ...
But the question, have intention of understand, if exists any reason ....beyond the explicit motive that is to make immutable
k

karelpeeters

11/10/2017, 12:33 PM
Are you asking about the general motivation for immutability? If an object is immutable you can pass it around freely without having to worry about someone else modifying it. Consider for example the String class, when I do something like this:
Copy code
val a = "Test"
foo(a)
//here I'm 100% sure a is still "Test", foo couldn't have modified it
l

Leandro Cavalheiro

11/10/2017, 12:44 PM
The motivation for immutablity..i understand ... my question referred the class.. if have any reason for always uses immutablity in the examples...
k

karelpeeters

11/10/2017, 12:45 PM
It's pretty much the default: use
val
whenever you can and switch to
var
only if you really need a mutable variable.
2
l

Leandro Cavalheiro

11/10/2017, 12:53 PM
Understand... thanks for explanation
👍 1
c

cedric

11/10/2017, 10:12 PM
@karelpeeters
val
and
var
are about making the references constant, they have nothing to do with making the object mutable/immutable /cc @Leandro Cavalheiro
👍 1
k

karelpeeters

11/10/2017, 10:26 PM
@cedric I misunderstood his question as "why is immutability useful?", so I tried to explain that. Thanks for clarifying!
👍 1
In hindsight my example was pretty bad too.
👍 1
2 Views