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

OperatorsKotlin

Operators Problem Overview


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.

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 +"\"")

What are the other uses, and what are they do? Is there a general meaning of the arrow operator in Kotlin?

Operators Solutions


Solution 1 - Operators

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 <T> sort(comparator:(T,T) -> Int){
       }
    

Details about Kotlin grammar are in the documentation in particular:

Solution 2 - Operators

The -> is a separator. It is special symbol used to separate code with different purposes. It can be used to:

  • Separate the parameters and body of a lambda expression

      val sum = { x: Int, y: Int -> x + y }
    
  • Separate the parameters and return type declaration in a function type

      (R, T) -> R
    
  • Separate the condition and body of a when expression branch

      when (x) {
          0, 1 -> print("x == 0 or x == 1")
          else -> print("otherwise")
      }  
    

Here it is in the documentation.

Solution 3 - Operators

From the Kotlin docs:

> ->

> - separates the parameters and body of a lambda expression

> - separates the parameters and return type declaration in a function type

> - separates the condition and body of a when expression branch

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGergely LukacsyView Question on Stackoverflow
Solution 1 - OperatorsmiensolView Answer on Stackoverflow
Solution 2 - OperatorsdonturnerView Answer on Stackoverflow
Solution 3 - Operatorssmo0fView Answer on Stackoverflow