How to declare a Function in Kotlin?

0 min read 137 words

Functions are reusable pieces of code, often called Blocks, that as the name suggests, act as building blocks to piece together a program.

Each language has its own keyword for defining a function block.

What is fun?

The fun keyword in Kotlin denotes a function, or method to wrap a reusable code block.

fun prepends the name of a function as illustrated below.

fun functionName(): String {
    return "A String"
}

The structure of a Kotlin function

The function can take any number of parameters, and a return type.

fun nameOfFunction(variable: InputType, anotherVariable: SomeType): ReturnType {
    // function code goes in here
    return somethingThatMatchesTheReturnType
}

A Kotlin function without a return value

If the function does not return a value, you can explicitly set its return type to Unit.

fun doesNotReturnAnything(yourName: String): Unit {
  println("Hello "+yourName)
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts