It would be great if the “Convert Java to Kotlin” ...
# intellij
c
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
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
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() {
            
        }
    }

}
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
dog?.hairColor = ""
a
Thank you, I created a couple of issues: https://youtrack.jetbrains.com/issue/KTIJ-6067, https://youtrack.jetbrains.com/issue/KTIJ-6068. Please vote/watch.
c
Thanks!