Читать книгу Programming Kotlin Applications - Бретт Мак-Лахлин, Brett McLaughlin - Страница 47
Constants Can't Change (Sort of)
ОглавлениеHere's the code causing the problem:
// Create another person val rose = Person("Rose", "Bushnell") rose.lastName = "Bushnell-Truesby"
If you try to run this code, you'll get an error like this:
Error: Kotlin: Val cannot be reassigned
One of the things that is fairly unique about Kotlin is its strong stance on variables. Specifically, Kotlin allows you to not just declare the type of a variable, but also whether that variable is a mutable variable, or a constant variable.
NOTE The terminology here is a bit confusing, so take your time. Just as with methods being declared with the fun
keyword, the idea of a constant variable takes a little getting used to.
When you declare a variable in Kotlin, you can use the keyword val
, as you've already done:
val brian = Person("Brian", "Truesby")
But you can also use the keyword var
, something you haven't done yet. That would look like this:
var brian = Person("Brian", "Truesby")
First, in both cases, you end up with a variable; val
does not stand for value, for example, but is simply another way to declare a variable, alongside var
. When you use val
, you are creating a constant variable. In Kotlin, a constant variable can be assigned a value once, and only once. That variable is then constant and can never be changed.
You created the lastName
variable in Person
with this line:
class Person(val firstName: String, val lastName: String) {
That defines lastName
(and firstName
) as a constant variable. Once it's passed in and assigned when the Person
instance is created, it can't be changed. That makes this statement illegal:
rose.lastName = "Bushnell-Truesby"
To clear up the odd error from earlier, what you need instead is for lastName
to be a mutable variable; you need it to be changeable after initial assignment.
NOTE Not to beat a hairy and somewhat fluffy dog to death, but here is another reason to use mutator over setter; a mutator allows you to mutate a mutable variable. This aligns the terminology much more cleanly than using “setter.”
So change your Person
constructor to use var
instead of val
. This indicates that firstName
and lastName
can be changed:
class Person(var firstName: String, var lastName: String) {
Now you should be able to compile the program again, without error. In fact, once you've done that, make a few other tweaks. You want to end up with your code looking like Listing 1.7.