Initialize fields only once

Report a typo

Here's a class named SimpleClass. It has a single field of the String type and a method to initialize the field. The method writes a given value to the field if it's empty. Otherwise, the method does nothing.

class SimpleClass {

    var str: String = ""

    fun initWithString(str: String) {
        if (this.str.isEmpty()) { // 1
            this.str = str        // 2
        }                         // 3
    }
}

Multiple threads are trying to invoke the method initWithString on the same instance. How can you synchronize this code so that the field of the instance gets initialized only once? Select all correct cases:

Select one or more options from the list
___

Create a free account to access the full topic