What does the arrow (“->”) operator do in Kotlin?

前端 未结 3 1638
耶瑟儿~
耶瑟儿~ 2020-12-05 04:09

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 a

3条回答
  •  我在风中等你
    2020-12-05 04:40

    The -> is part of Kotlin's syntax (similar to Java's lambda expressions syntax) and can be used in 3 contexts:

    • 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 expressions where it separates parameters from function body

        val lambda = { a:String -> "hi!" }
        items.filter { element -> element == "search"  }
      
    • function types where it separates parameters types from result type e.g. comparator

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

    Details about Kotlin grammar are in the documentation in particular:

    • functionType
    • functionLiteral
    • whenEntry

提交回复
热议问题