CodeBlanks Logo Icon CodeBlanks

Function types

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

Main.kt
// a format variable of function type
// n -> "Number: $n" lambda body
// call format in main and print

Sample solution

Main.kt
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) -&gt; String</code> express?

Main.kt
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

Question
val format: (Int) ____ String = { n -> "Number: $n" }
Answer
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

All lessons in Intermediate