Uknown behavior


#1

Hi guys,

Today I was writing a piece of code and found some strange stuff:

    private val properties = mutableMapOf<Any, Any>()
    
    override fun setProperty(key: Any, innerKey: Any, value: Any?) {
        synchronized(properties ) {
            val innerMap = properties[key] as? MutableMap<*, *>
            if (innerMap == null) {
                if (value == null)
                    return
                properties.put(key, mutableMapOf<Any, Any>())
            } else if (value == null) {
                innerMap.remove(innerKey)
                if (innerMap.isEmpty())
                    properties.remove(innerMap)
            }
        }
    }

in this method I have an error: ‘if’ must have both main and ‘else’ branches if used as an expression
for:

    if (innerMap.isEmpty())
            properties.remove(innerMap)

maybe there is some wrong but can someone explain what exactly wrong with it ?


#2

The synchronized function receives a lambda that returns something, so the compiler thinks your if is an expression.
You need to add a result for the lambda like:

synchronized(properties ) {
    if (innerMap == null) {
       ...
    }

    Unit // <- result for the lambda
}

I think calling it this way also works:

synchronized<Unit>(properties) {
    ...
}

#3

Yeah, this is fixed issue.

Thanks.