Getting a val from a var - aka SharedObject is evil


#1

I was just doing some code that was parsing some XML and firing an event callback.  As part of the code, outside my loop I have:

var customer: Customer = Customer()

as I look around the code, I reassign the customer variable, and at some point call my callback(customer) with, what I assumed was a unique instance of Customer.

Only, it seems that ‘customer’ doesn’t actually hold a Customer instance, but rather a SharedObject which -contains- a Customer - which meant when I changed my code to fire off the callback via an Executor I started to get race conditions as the SharedObject was passed around instead.

To get around this, I now also have

val callbackCustomer = customer

before which I pass into the Executor.

This looks like a rather nasty gotcha/trap for new players which I only found when stepping thru with the debugger.

Shouldnt the compiler fail given that my callback takes a Customer, not a SharedObject?


#2

Function literals capture vars as vars, i.e. as mutable values (implemented with shared objects). The use case for this is, for example:

``


var count = 0
myCollection.forEach {
  if (condition)
  count++
}

The Java mindset makes this kind of twofold: Java doesn’t allow this, so you assume that Kotlin does not allow this (and should complain) and expect some different behavior…