Single-expression functions in Kotlin

Level 3164 keystrokes

A function whose body is one expression can be written with = instead of braces and return. The return type is inferred from the expression: Int, Boolean and String here.

Kotlin code

// = replaces { return ... }; the return type Int is inferred from x * x
1fun square(x: Int) = x * x
// The comparison makes the return type Boolean: true when n is divisible by 2
2fun isEven(n: Int) = n % 2 == 0
// A string template: the return type is String
3fun greet(name: String) = "Hello, $name!"
4
// Print 25
5println(square(5))
// 4 % 2 == 0, so print true
6println(isEven(4))
// Print Hello, Kotlin!
7println(greet("Kotlin"))

Output

25
true
Hello, Kotlin!
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Kotlin code and how often they appear.

  • (× 9
  • )× 9
  • =× 5
  • "× 4
  • :× 3
  • ,× 1
  • !× 1
  • *× 1
  • %× 1
  • $× 1

More Kotlin examples at level 3

← Kotlin typing practice