-
Notifications
You must be signed in to change notification settings - Fork 0
Mutable and Immutable
Rajesh Khadka edited this page Apr 19, 2019
·
1 revision
An object whose attributes can change after they have been created. Mutable objects have methods to change the values of attributes. kotlin StringBuilder, java.util.Date .
class User(var name: String) fun main(args: Array<String>) {
var user = User("Bob")
user.name = "James"
print(user.name)
}An object whose attributes cannot be changed after they have been created. kotlin String, Integer and Long .
var localDate = LocalDate.of(2015, 1, 1)
//tried to add one year on local date
localDate.plusYears(1)
print(localDate)We have increased the year by 1 which doesn't have an effect on a local object. output
2014-1-1Immutable objects are thread safe.
It's much easier for the garbage collector to make logical decisions about immutable objects
- Defining class as final in case of java but Kotlin classes are by default final.
- Not providing any methods to change a variable in case of java. In Kotlin don't define a variable as var in class.
| Mutable | Immutable |
|---|---|
User(name: String) |
User(var name: String) |