Kotlin 中的箭头(“->")运算符有什么作用? [英] What does the arrow ("->") operator do in Kotlin?
问题描述
可能有点宽泛的问题,但官方文档甚至没有提到作为独立实体的箭头运算符(或语言结构,我不知道哪个短语更准确).
Probably a little bit broad question, but the official documentation doesn't even mentioning the arrow operator (or language construct, I don't know which phrase is more accurate) as an independent entity.
最明显的用途是when条件语句,它用于将表达式分配给特定条件:
The most obvious use is the when conditional statement, where it is used to assign an expression to a specific condition:
val greet = when(args[0]) {
"Appul" -> "howdy!"
"Orang" -> "wazzup?"
"Banan" -> "bonjur!"
else -> "hi!"
}
println(args[0] +" greets you: ""+ greet +""")
其他用途是什么,它们有什么作用?Kotlin 中箭头操作符有一般含义吗?
What are the other uses, and what are they do? Is there a general meaning of the arrow operator in Kotlin?
推荐答案
->
是 Kotlin 语法的一部分(类似于 Java 的 lambda 表达式语法) 并且可以在 3 个上下文中使用:
The ->
is part of Kotlin's syntax (similar to Java's lambda expressions syntax) and can be used in 3 contexts:
when
将匹配/条件"部分与结果/执行"块分开的表达式
when
expressions where it separates "matching/condition" part from "result/execution" block
val greet = when(args[0]) {
"Apple", "Orange" -> "fruit"
is Number -> "How many?"
else -> "hi!"
}
将参数与函数体分开的 lambda 表达式
lambda expressions where it separates parameters from function body
val lambda = { a:String -> "hi!" }
items.filter { element -> element == "search" }
将参数类型与结果类型分开的函数类型,例如比较器
fun <T> sort(comparator:(T,T) -> Int){
}
有关 Kotlin 语法的详细信息在文档中 尤其是:
Details about Kotlin grammar are in the documentation in particular:
这篇关于Kotlin 中的箭头(“->")运算符有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!