我嘗試撰寫一個可以插入任何運算式的函式,以記錄值:
val x = (2.debug() 3.debug()).debug("2 3")
但是我寫了以下無限回圈:
fun debug (message: String) {
Log.d (R.string.app_name.toString(), message) }
fun <T> T.debug (tag: String = "value"): T {
debug ("$tag: $this")
return this
}
我的目標是撰寫一個“普通”函式(第 1 個)和一個擴展函式(第 2 個),擴展函式應該呼叫普通函式。
我的代碼中的問題是:擴展函式呼叫自身而不是普通函式。我不明白這一點,因為我沒有在擴展函式中指定實體接收器。
如何解決這個問題?
uj5u.com熱心網友回復:
鑒于每個函式中有不同的引數名稱,您可以更改第二個函式以使用命名引數呼叫第一個函式:
fun <T> T.debug (tag: String = "value"): T {
debug (message = "$tag: $this")
return this
}
uj5u.com熱心網友回復:
我找不到剝離this擴展方法的方法,所以最好的方法是創建不同名稱的包裝器:
fun <T> T.debug (tag: String = "value"): T {
debugWrapper( "$tag: $this")
return this
}
fun debug (message: String) {
Log.d ("tag", message)
}
private fun debugWrapper (message: String) {
debug(message)
}
我認為您希望保留現有的電話debug,這會交付。
我試圖查看反編譯代碼(為清楚起見,減去默認引數)希望通過名稱空間區分它們:
public final class TestclassKt {
public static final Object debug(Object $this$debug, @NotNull String tag) {
Intrinsics.checkNotNullParameter(tag, "tag");
debug($this$debug, tag ": " $this$debug);
return $this$debug;
}
public static final void debug(@NotNull String message) {
Intrinsics.checkNotNullParameter(message, "message");
Log.d("tag", message);
}
}
但是這 2 個方法在同一個命名空間中,區分它們的唯一方法是通過引數。
我認為你已經破壞了 Kotlin。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/535154.html
標籤:科特林
