Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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?

like image 651
Gergely Lukacsy Avatar asked Mar 07 '17 10:03

Gergely Lukacsy


People also ask

What does -> mean in Kotlin?

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 }

What does () -> in Java mean?

Basically, the -> separates the parameters (left-side) from the implementation (right side). The general syntax for using lambda expressions is. (Parameters) -> { Body } where the -> separates parameters and lambda expression body.

What does the operator do in Kotlin?

Kotlin has a set of operators to perform arithmetic, assignment, comparison operators and more. You will learn to use these operators in this article. Operators are special symbols (characters) that carry out operations on operands (variables and values).

What are lambdas in Kotlin?

Lambda expression is a simplified representation of a function. It can be passed as a parameter, stored in a variable or even returned as a value. Note: If you are new to Android app development or just getting started, you should get a head start from Kotlin for Android: An Introduction.


1 Answers

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:

  • functionType
  • functionLiteral
  • whenEntry
like image 103
miensol Avatar answered Sep 21 '22 15:09

miensol