箭头(“->")运算符在Kotlin中做什么? [英] What does the arrow ("->") operator do in Kotlin?

查看:826
本文介绍了箭头(“->")运算符在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的

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"  }
    

  • 函数类型,其中将参数类型与结果类型分开,例如comparator

      fun <T> sort(comparator:(T,T) -> Int){
      }
    

  • 有关Kotlin语法的详细信息,请参见文档中的 :

    Details about Kotlin grammar are in the documentation in particular:

    • functionType
    • functionLiteral
    • whenEntry

    这篇关于箭头(“->")运算符在Kotlin中做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆