https://kotlinlang.org logo
#getting-started
Title
# getting-started
m

Mark

02/04/2022, 10:30 AM
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

gildor

02/04/2022, 10:33 AM
It cannot infer type without it correctly, because if returns Unit as inferred type, but else set it to String
j

Joffrey

02/04/2022, 10:34 AM
@gildor why though? Technically it could infer the whole
if
expression as
Any?
g

gildor

02/04/2022, 10:35 AM
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

Joffrey

02/04/2022, 10:36 AM
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

gildor

02/04/2022, 10:37 AM
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

Joffrey

02/04/2022, 10:37 AM
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

gildor

02/04/2022, 10:38 AM
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

Mark

02/04/2022, 10:44 AM
By the way, if I uncomment the null, then Android Studio gives a warning that
null
is unused.
j

Joffrey

02/04/2022, 10:49 AM
@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

Mark

02/04/2022, 11:00 AM
@Joffrey totally agree, I just wanted to point out that small bug with the warning message.
👍 1
v

Victor Petukhov

02/04/2022, 11:57 AM
@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

Mark

02/10/2023, 2:15 PM
6 Views