Reputation: 1567
I'm curious why it's possible to call kotlin's constructor with default param but not a method from java code?
For example:
class Test(val test: String = "")
Java client:
void test() {
new Test();
}
It's ok.
But if i want to do the same trick with method, it's not possible:
class Test {
fun x(x: Int = 5) { }
}
Java client, compilation error:
void test() {
new Test().x();
}
In the decompiled to java bytecode of the method i see
x$default
method. It is static and I can't call it from java(idea doesn't allow me to do it). And only addition of
@JvmOverloads
annotation on the kotlin's method with default arg creates one more method which is accessible from the java side.
The question is why there are two approaches how to call kotlin's defaults from java? Why not to do everything accessible/not accessible by default? Is it a bad design or there was serious reason to do so?
Upvotes: 3
Views: 1229
Reputation: 147911
I believe, the considerations behind the current design were based on the fact that presence of a default (no-argument) constructor in a class is a widely used convention on JVM: there are many libraries and frameworks that rely on it (e.g. dependency injection tools, JSR-305). So, generating a no-argument constructor when there are default values for all of the parameters supports these use cases and might be expected by the users.
On contrary, functions usually don't have default values for all of their parameters, and I don't think it's needed by any idiom in the Java world. Moreover, you can expect many functions with default values in Kotlin classes, and generating the overloads for them by default would result into undesirable method count growth, which is in particular important for Android.
Upvotes: 3