含義:方法的重載叭喜,類似于在java中對(duì)多個(gè)構(gòu)造函數(shù)咒林、多個(gè)方法的重載
可能還是云里霧里肆资,直接上代碼造虏,代碼解釋一切:
如果我們?cè)賙otlin中寫(xiě)如下代碼:
fun f(a: String, b: Int = 0, c: String="abc"){
}
相當(dāng)于在Java中聲明
void f(String a, int b, String c){
}
默認(rèn)參數(shù)沒(méi)有起到任何作用。
但是如果使用的了@JvmOverloads注解:
@JvmOverloads fun f(a: String, b: Int=0, c:String="abc"){
}
相當(dāng)于在Java中聲明了3個(gè)方法:
void f(String a)
void f(String a, int b)
void f(String a, int b, String c)
是不是很方便儿子,再也不用寫(xiě)那么多重載方法了趟薄。
注:該注解也可用在構(gòu)造方法和靜態(tài)方法。
Kotlin中代碼:
class EmptyView
@JvmOverloads constructor (context: Context, attrs: AttributeSet? =null,
defStyle: Int =0) : LinearLayout(context, attrs, defStyle) {
}
相當(dāng)Java中的:
public class EmptyView extends RelativeLayout {
? ? public EmptyView(Context context) {
? ? ? ? this(context, null);
? ? }
? ? public EmptyView(Context context, AttributeSet attrs) {
? ? ? ? this(context, attrs, 0);
? ? }
? ? public EmptyView(Context context, AttributeSet attrs, int defStyleAttr) {
? ? ? ? super(context, attrs, defStyleAttr);
? ? }
}