Kotlin有一个非常好的特性,就是扩展函数,非常好用如下
package com.plbear.leakcanary
import android.app.Activity
import android.util.Log
fun logcat(msg: String?) {
Log.e("yanlog", msg ?: "null")
}
fun Activity.myStop() {
this.finish()
}
fun String?.toNotNUll(tmp: String): String {
return this ?: tmp
}
我们反编译看下编译完成之后是什么
package com.plbear.leakcanary;
import android.app.Activity;
import android.util.Log;
import kotlin.Metadata;
import kotlin.jvm.internal.Intrinsics;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/* compiled from: Utils.kt */
public final class UtilsKt {
public static final void logcat(@Nullable String msg) {
if (msg == null) {
msg = "null";
}
Log.e("yanlog", msg);
}
public static final void myStop(@NotNull Activity $this$myStop) {
Intrinsics.checkNotNullParameter($this$myStop, "$this$myStop");
$this$myStop.finish();
}
@NotNull
public static final String toNotNUll(@Nullable String $this$toNotNUll, @NotNull String tmp) {
Intrinsics.checkNotNullParameter(tmp, "tmp");
return $this$toNotNUll != null ? $this$toNotNUll : tmp;
}
}
哦,原来就是用static来实现,将扩展的类作为第一个参数传入即可。就这样。
注,UtilsKt的类名是因为我们使用了Utils.kt的文件名,