MOOC List is learner-supported. When you buy through links on our site, we may earn an affiliate commission.
MOOC List is learner-supported. When you buy through links on our site, we may earn an affiliate commission.
Topics include:
- How references work with the JVM (simplified for beginners)
- The problem of Shared Mutable State (this is bad)
- How to avoid Shared Mutable State by introducing Immutability (const val and val properties) to your code
- How and when it makes sense to use var references
- How to make classes, and the data class construct
As discussed in this class, one of the most difficult technical challenges which programmers face, is dealing with Shared Mutable State (Shared change-able data). Our first defense against such problems, is to work with Immutable Data as often as possible.
Using either the try.kotlinlang.org online IDE, or your own preferred IDE, write a simple program which has:
- A data class of some kind with at least two val properties, such as a "User" data class
- A main function which serves as the entry point of the program's execution
Instructions:
1. Create a val reference of the same type as your data class (i.e. instantiate your data class)
2. Create a second val reference from the first val reference, using the copy() function (this function comes from the data class keyword).
3. Change at least one of the properties in this new val reference, by using default arguments within the copy() function.
The purpose of this small project is to get you used to working with immutable data and vals. At first it can appear impossible to make a working program using data classes with only val references, but by using the copy function, we can create new immutable copies based on old data, mutating only the properties we wish to!
MOOC List is learner-supported. When you buy through links on our site, we may earn an affiliate commission.
MOOC List is learner-supported. When you buy through links on our site, we may earn an affiliate commission.