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

svenjacobs

01/23/2023, 10:16 AM
Guys, I have a very weird Java / Kotlin interoperability problem with the
Boolean
type. I’m using a Java API which defines two functions:
void setSomething(boolean enabled)
and
void setSomething(Boolean enabled)
, where
Boolean
is
java.lang.Boolean
here. The first function with the primitive Java type is marked deprecated. I’m trying to call the second function from Kotlin code but every time Kotlin tries to unbox the boolean into the primitive type, so it calls the deprecated function. How can I force Kotlin to use the boxed object type? For example I tried
Copy code
api.setSomething(Boolean.valueOf(true))
but it’s still complaining.
v

Vampire

01/23/2023, 10:19 AM
Just a guess, but maybe
true as java.lang.Boolean
?
s

svenjacobs

01/23/2023, 10:20 AM
Unfortunately not, this gives a type error
Copy code
Required: kotlin.Boolean
Found: java.lang.Boolean
😞 1
and
true as Boolean
is just marked as an obsolete cast, still tries to call the deprecated function.
v

Vampire

01/23/2023, 10:22 AM
Maybe
true as Boolean?
?
👌 1
🎉 1
s

svenjacobs

01/23/2023, 10:23 AM
Yes, that’s it! Thank you!
It’s been so long since I last coded Java. I totally forgot that every object reference is nullable by default there 😅
👌 1
p

phldavies

01/23/2023, 10:41 AM
It’s worth keeping in mind that Kotlin/JVM treats
Boolean
as the unboxed
boolean
primitive and
Boolean?
as the boxed
java.lang.Boolean
(see here). Similarly to numbers.
👍🏼 1
👍 1
thank you color 1
7 Views