← Kotlin tutorial

Kotlin

Functions

Declare a function with fun name(params): ReturnType { ... }. For a one-line function, you can skip the braces and use = instead.

Example: a single-expression function

fun greet(name: String): String = "Hello, $name!"

fun main() {
    println(greet("Chidi"))
}
Hello, Chidi!

This is the same underlying idea as Dart's arrow functions or a Python lambda, a function whose entire body is one expression doesn't need the full { return ... } ceremony. Kotlin can even infer the return type here from the expression itself, though writing it explicitly (as above) keeps the function's contract clear at a glance.

Example
fun greet(name: String): String = "Hello, $name!"

fun main() {
    println(greet("Chidi"))
}
Output
Hello, Chidi!
Ready to go further?

These free tutorials are a preview of what a Code Secure Academy cohort covers, project work and all.

Explore our tracks

Cookie preferences

Choose what you're comfortable with. You can change this any time from the footer.

Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account