它与扩展函数有什么关系?为什么with a function不是关键字?
似乎没有关于这个主题的明确文档,只有关于extensions的知识假设。
发布于 2019-04-07 06:18:13
简单地说(没有任何额外的单词或复杂情况),“接收器”是在扩展函数或类名中扩展的类型。使用上述答案中给出的示例
fun Foo.functionInFoo(): Unit = TODO()类型"Foo“是”接收者“
var greet: String.() -> Unit = { println("Hello $this") }类型"String“是"Receiver”
附加提示:注意句号(.)之前的类。在"fun“(函数)声明中
fun receiver_class.function_name() {
//...
}发布于 2020-10-20 05:20:49
对象之前的对象实例。是接收器。这实际上就是您将在其中定义这个lambda的“范围”。这就是您需要知道的全部内容,因为您将在lambda中使用的函数和属性(变量、伴生等)将在此作用域中提供。
class Music(){
var track:String=""
fun printTrack():Unit{
println(track)
}
}
//Music class is the receiver of this function, in other words, the lambda can be piled after a Music class just like its extension function Since Music is an instance, refer to it by 'this', refer to lambda parameters by 'it', like always
val track_name:Music.(String)->Unit={track=it;printTrack()}
/*Create an Instance of Music and immediately call its function received by the name 'track_name', and exclusively available to instances of this class*/
Music().track_name("Still Breathing")
//Output
Still Breathing您可以使用和它将具有的所有参数和返回类型来定义此变量,但在定义的所有构造中,只有对象实例可以调用var,就像它将扩展函数提供给它并提供其构造一样,从而“接收”它。因此,接收器将被松散地定义为使用lambdas的惯用风格为其定义扩展函数的对象。
发布于 2020-09-12 08:40:04
通常,在Java或Kotlin中,您的方法或函数具有T类型的输入参数。在Kotlin中,您还可以具有接收T类型的值的扩展函数。
如果您有一个接受字符串参数的函数,例如:
fun hasWhitespace(line: String): Boolean {
for (ch in line) if (ch.isWhitespace()) return true
return false
}将参数转换为接收器(您可以使用IntelliJ自动完成):
fun String.hasWhitespace(): Boolean {
for (ch in this) if (ch.isWhitespace()) return true
return false
}现在我们有了一个接收字符串的扩展函数,我们可以用this访问值
https://stackoverflow.com/questions/45875491
复制相似问题