Skip to content

Mutable and Immutable

Rajesh Khadka edited this page Apr 19, 2019 · 1 revision

Mutable

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)
   }

Immutable

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-1

Concurrency

Immutable objects are thread safe.

Garbage Collection

It's much easier for the garbage collector to make logical decisions about immutable objects

How to achieve immutability

  • 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)
Clone this wiki locally