如何从lambda引用外部函数?

Cod*_*Man 4 kotlin

问题出在评论中.我想引用外部函数append,而不是那个中定义的函数,StringBuilder我该怎么做?

fun append(c: Char) {
    println("TEST")
}

fun sbTest() = with(StringBuilder()) {
    for(c in 'A'..'Z') {
        append(c) // how do I refer to the append function declared above?
    }
    toString()
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以引入一个函数引用变量,如下所示:

val f = ::append

并打电话f而不是append,但还有另一种方式吗?

Zoe*_*Zoe 5

问题在于,任何内部调用都会with影响外部函数,因为它this是引入的.如果您有一个具有相同签名的函数的类和顶级函数,则会出现同样的问题.

显而易见的选择只是重新命名它.此外,您所拥有的功能与实际功能相比并不具有描述性.但如果由于某种原因无法重命名,还有其他选择.

顶级方法可以通过Kotlin中的包引用,例如com.some.package.method.它也可以这样导入,这是最常用的方法.很少有方法被称为com.some.package.method().

像Python一样,Kotlin允许as进口.这意味着,您可以这样做:

package com.example;

// This is the important line; it declares the import with a custom name.
import com.example.append as appendChar; // Just an example name; this could be anything ***except append***. If it's append, it defeats the purpose

fun append(c: Char) {
    println("TEST")
}

fun sbTest() = with(StringBuilder()) {
    for(c in 'A'..'Z') {
        appendChar(c) 
    }
    toString()
}
Run Code Online (Sandbox Code Playgroud)

或者,正如我所提到的,您可以添加包:

for(c in 'A'..'Z') {
    com.example.append(c) 
}
Run Code Online (Sandbox Code Playgroud)

val f = ::append当然也是一个选项,无论哪种方式,重命名函数比使用as或常量创建导入更容易,假设您有权访问该函数(并且它不属于依赖项).


如果您的文件位于程序包之外(我不建议您这样做),则可以将导入声明为:

import append as appendChar
Run Code Online (Sandbox Code Playgroud)