Function types
- Kotlin course
- Intermediate
- Lesson 53/116
- 5 min
Learn function types with (Int) -> String.
Function type
A function type expresses a function's signature as a type. It is written as (Int) -> String; parameter types go in parentheses, the return type after the arrow.
Example: val format: (Int) -> String = { n -> "Number: $n" }. Here format is a function that takes an Int and returns a String. Calling format(5) returns "Number: 5". Function types let you carry functions as values. This is the foundation of higher-order functions.
The format function
A function type variable gets a lambda or a function reference. It is called by the variable name.
Example: val format: (Int) -> String = { n -> "Number: $n" }. Calling format(5) returns "Number: 5". n is the lambda parameter; its type is inferred as Int. A function type lets you pass functions as parameters or keep them in lists. You can also declare listOf<(Int) -> String>.
Practice The format function type
Declare val format: (Int) -> String = { n -> "Number: $n" }. In main call println(format(5)).
Starter code
// a format variable of function type
// n -> "Number: $n" lambda body
// call format in main and printSample solution
val format: (Int) -> String = { n -> "Number: $n" }
fun main() {
println(format(5))
}Expected output
Number: 5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the type <code>(Int) -> String</code> express?
In a function type, -> marks the return type.- A function taking Int and returning String Correct answer
- A conversion from Int to String
- A pair of two Ints
- A function turning String into Int
Explanation: (Int) -> String is a function type that takes Int and returns String.
2 Complete the function type definition
val format: (Int) ____ String = { n -> "Number: $n" }
val format: (Int) -> String = { n -> "Number: $n" }
Explanation: -> marks the return type.
3 Match the function type parts
| Term | Meaning |
|---|---|
(Int) -> String |
Function type |
{ n -> ... } |
Lambda body |
format(5) |
Call |
"Number: 5" |
Return value |