@JvmOverloads:
Instructs the Kotlin compiler to generate overloads for this function that substitute default parameter values.
If a method has N parameters and M of which have default values, M overloads are generated: the first one takes N-1 parameters (all but the last one that takes a default value), the second takes N-2 parameters, and so on.
指示Kotlin编译器为此函数生成替换默认参数值的重载。
如果一个方法有N个参数,其中M个具有默认值,则会生成M个重载:第一个重载使用N-1个参数(除了最后一个具有默认值),第二个重载N-2个参数,依此类推上。
通常,如果您使用默认参数值编写Kotlin函数,则该函数在Java中仅作为具有所有参数存在的完整签名可见。如果希望向Java调用者公开多个重载,则可以使用 @JvmOverloads
注释。
举例:
class Circle @JvmOverloads constructor(centerX: Int, centerY: Int, radius: Double = 1.0) {
@JvmOverloads fun draw(label: String, lineWidth: Int = 1, color: String = "red") { /*...*/ }
}
对于具有默认值的每个参数,这将产生一个额外的重载,该重载将删除此参数及其在参数列表中右侧的所有参数。在此示例中,将生成以下内容:
// Constructors:
Circle(int centerX, int centerY, double radius)
Circle(int centerX, int centerY)
// Methods
void draw(String label, int lineWidth, String color) { }
void draw(String label, int lineWidth) { }
void draw(String label) { }
* 1.注释还适用于构造函数,静态方法等。它不能用于抽象方法,包括在接口中定义的方法。
* 2.如果类具有所有构造函数参数的默认值,则将为其生成一个公共的无参数构造函数。即使@JvmOverloads
未指定注释,此方法也有效。