why is kotlin not creating a default constructor f...
# android
s
why is kotlin not creating a default constructor for the fragments? How do I add an empty default constructor? Some devices are crashing because there's no default constructor in the fragment. 😐
s
are you defining custom constructor for fragments?
s
yes, it has a constructor for the layout resource, but it works fine in every device I test
but crashlytics is showing a crash from a device
if I create a kotlin fragment with no custom constructor, just a basic example, if I convert the bytecode to java it also doesn't have the default constructor, woot?
c
It only ever creates a default constructor if you didn’t manually create one. That’s the same behavior as Java, too…
Also, default parameters don’t create separate functions/constructors. There’s some more clever code-gen making them work behind-the-scenes that minimizes the number of generated methods. But you can add
@JvmOverloads
to the constructor with default parameters to explicitly ask it to make multiple overloaded constructors https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#overloads-generation
s
yes, tried the constructor with default parameters and the generated bytecode converted to java does not have a default constructor with empty body as required for the fragments in android.
this issue is interesting… because only some devices are crashing.
c
Might be an Android version thing, fragments with a layout ID are a fairly recent thing. Either way, just using the constructor with default parameters is not safe, since the framework or other libraries will be creating it with reflection, so you should use
@JvmOverloads
on the primary constructor to make sure that the default one with no layoutId also gets generated
s
I have no idea where is the error…
@JvmOverloads
is not working…
I added the question to SO if someone else wants to take a look and answer
Copy code
class TestJavaFragment2 @JvmOverloads constructor(private val i: Int = 0) : Fragment()
results in java code without the empty private constructor