2021-10-11 Kotlin中@JvmOverloads 注解

Kotlin中@JvmOverloads 注解

在kotlin中声明一个函数,函数中有默认参数值的参数,实际上默认参数值没有起到作用。

fun f(a: String, b: Int = 0, c: String="abc"){
    
    
    ...
}

就其实相当于

void f(String a, int b, String c){
    
    
}

实际上默认的参数值在方法调用的时候就被覆盖了

但是如果说在 fun 前面添加了**@JvmOverloads**注解,暴露出多个重载的方法。

@JvmOverloads fun f(a: String, b: Int=0, c:String="abc"){
    
    
}

相当于java中:

void f(String a)
void f(String a, int b)
void f(String a, int b, String c)

并且此时在没有该值的构造器中,默认值已经是传过来的参数值了,就比如 第一个构造器中没有传入b的值,但是b在默认传参中已经赋值为0了。

注:该注解也可用在构造方法和静态方法。

class MyLayout: RelativeLayout {
    
    
 
   @JvmOverloads
   constructor(context:Context, attributeSet: AttributeSet? = null, defStyleAttr: Int = 0): super(context, attributeSet, defStyleAttr)
}

相当于java:

public class MyLayout extends RelativeLayout {
    
    
    public MyLayout(Context context) {
    
    
        this(context, null);
    }

    public MyLayout(Context context, AttributeSet attrs) {
    
    
        this(context, attrs, 0);
    }

    public MyLayout(Context context, AttributeSet attrs, int defStyleAttr) {
    
    
        super(context, attrs, defStyleAttr);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_45204129/article/details/120707356