Sobes.tech
Junior

What are lambda expressions from the perspective of syntax in Java and Kotlin?

sobes.tech AI

Answer from AI

In Java:

// Lambda expression for a functional interface with one method
(parameters) -> {
    // Expression body
}

// Example with functional interface Consumer
Consumer<String> consumer = (s) -> System.out.println(s);

// Example with functional interface Function
Function<Integer, String> function = (i) -> String.valueOf(i);

// Example without parameters
Runnable runnable = () -> System.out.println("Hello");

In Kotlin:

// Lambda expression
{ parameters ->
    // Expression body
}

// Example with one parameter
val printString: (String) -> Unit = { s -> println(s) }

// Example with implicit 'it' parameter
val printIt: (String) -> Unit = { println(it) }

// Example with multiple parameters
val sum: (Int, Int) -> Int = { a, b -> a + b }

// Example without parameters
val sayHello: () -> Unit = { println("Hello") }

Key differences:

Aspect Java Lambda Kotlin Lambda
Syntax (parameters) -> { body } { parameters -> body }
Type Functional interface Functional type
Implicit it No Yes, if one parameter
Return value Determined by expression Last expression in the body