It would be great if the “Convert Java to Kotlin” feature in IntelliJ would default to using the optional
?
notation instead of force-unwrapping (
!!
) everything. I understand the force-unwrapping allows it to be more in a state where it can compile, but I assume most of us go through and replace all those with optionals anyway to ensure null safety. If there is a way of changing that default behavior, please let me know.
a
Alexey Belkov [JB]
03/10/2021, 11:18 AM
I believe J2K should be as smart as possible generally, so type inference and conversion should choose the most appropriate types (nullable/not null) and corresponding operators without a special setting.
Can you share a specific code example where J2K doesn't convert the code optimally? Please file an issue at http://kotl.in/issue.
c
Chris Ruddell
03/11/2021, 12:53 PM
Here’s a simple example I wrote to illustrate:
Copy code
public class Animal {
private Dog dog;
void adoptDog() {
dog = new Dog();
}
void groomDog() {
dog.hairColor = "";
dog.bark();
}
static class Dog extends Animal {
private String hairColor;
void bark() {
}
}
}
Chris Ruddell
03/11/2021, 12:56 PM
When you convert this to Kotlin, it results in:
Copy code
class Animal {
private var dog: Dog? = null
fun adoptDog() {
dog = Dog()
}
fun groomDog() {
dog!!.hairColor = ""
dog!!.bark()
}
internal class Dog : Animal() {
private val hairColor: String? = null
fun bark() {}
}
}
In addition to the
dog
variable being forced unwrapped, it won’t even compile because it has marked
hairColor
as a
val
. I understand it’s not perfect and expect to go over the code after conversion, but force-unwrapping seems like a bad default option compared to simply calling