我尝试编写一个可以插入到任何表达式中的函数,以便记录该值:
val x = (2.debug() + 3.debug()).debug("2+3")
Run Code Online (Sandbox Code Playgroud)
但我写了以下无限循环:
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
}
Run Code Online (Sandbox Code Playgroud)
我的目标是编写一个“正常”函数(第一个)和一个扩展函数(第二个),扩展函数应该调用正常函数。
我的代码中的问题是:扩展函数调用自身而不是普通函数。我不明白这一点,因为我没有在扩展函数中指定实例接收器。
如何解决这个问题?
鉴于每个函数中有不同的参数名称,您可以更改第二个函数以使用命名参数调用第一个函数:
fun <T> T.debug (tag: String = "value"): T {
debug (message = "$tag: $this")
return this
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
55 次 |
| 最近记录: |