Playing around with `buildMap` but please can some...
# getting-started
m
Playing around with
buildMap
but please can someone explain why this gives a compilation error (unless I uncomment the null):
Copy code
fun main() {
    buildMap {
        if (true) {
            println("test")
            // null
        } else {
            put("foo", "bar")
        }
    }
}
https://pl.kotl.in/sohJmyPiJ
g
It cannot infer type without it correctly, because if returns Unit as inferred type, but else set it to String
j
@gildor why though? Technically it could infer the whole
if
expression as
Any?
g
You can specify type explicitly, it will solve the problem: buildMap<String, String>
👍 1
Technically it could infer the whole 
if
 expression as 
Any?
I think because it’s not really an expression it’s BuilderInference
j
Yeah this works, also adding
Unit
after the
put
in the
else
branch works. Interestingly, adding
Unit
after the whole
if
is not sufficient, so it's not about the return value of the lambda expected by
buildMap
.
g
it’s not about the return value of the lambda expected by
Yes, it’s not about return value, it’s about builder interface inference
j
Yeah but I'd be interested in why the builder inference prevents this
if
from being legal. I expected the builder inference to look for
put
and infer the type based on that regardless of other structures and expressions. But I know nothing of the builder inference frankly 😄
g
I think it’s just a matter of implementation limitation, you right, it can find all possible branches and infer type, but it apparantly doesn’t do this
m
By the way, if I uncomment the null, then Android Studio gives a warning that
null
is unused.
j
@Mark I think the cleanest option when builder inference is moody is to explicitly specify the types in
buildMap
, as mentioned by Andrey. I wouldn't try to add
null
or
Unit
in the right places to fix the inference
m
@Joffrey totally agree, I just wanted to point out that small bug with the warning message.
👍 1
v
@Mark thanks for the report! Could you create an issue please? https://youtrack.jetbrains.com/issue/KT-51143 Will try to fix it soon.
👍 1
m