[英]Why it's possible to call kotlin's constructor with default param but not a method?
I'm curious why it's possible to call kotlin's constructor with default param but not a method from java code? 我很好奇为什么可以用默认参数调用kotlin的构造函数,而不用Java代码中的方法调用呢?
For example: 例如:
class Test(val test: String = "")
Java client: Java客户端:
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: Java客户端,编译错误:
void test() {
new Test().x();
}
In the decompiled to java bytecode of the method i see 在反编译为Java字节码的方法中我看到了
x$default
X $默认
method. 方法。 It is static and I can't call it from java(idea doesn't allow me to do it).
它是静态的,我不能从java中调用它(idea不允许我这样做)。 And only addition of
而且只有
@JvmOverloads
@JvmOverloads
annotation on the kotlin's method with default arg creates one more method which is accessible from the java side. 带有默认arg的kotlin方法的注释创建了另外一种方法,该方法可以从Java端访问。
The question is why there are two approaches how to call kotlin's defaults from java? 问题是,为什么有两种方法可以从Java调用kotlin的默认值? Why not to do everything accessible/not accessible by default?
为什么不使所有内容默认都可访问/不可访问? Is it a bad design or there was serious reason to do so?
这是一个不好的设计还是有严重的理由?
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 (eg dependency injection tools, JSR-305). 我相信,当前设计背后的考虑基于以下事实:在类中存在默认(无参数)构造函数是JVM上广泛使用的约定:有许多库和框架都依赖于它(例如,依赖项注入)工具,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. 相反,函数通常没有所有参数的默认值,而且我认为Java世界中的任何惯用法都不需要它。 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.
此外,您可以期望Kotlin类中的许多函数具有默认值,并且默认情况下为它们生成重载将导致不良的方法计数增长,这对于Android尤其重要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.