Menu
Coddy logo textTech

Declare A Function

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 55 of 93.

A function is a reusable block of code that performs a specific task. Instead of writing the same code multiple times, you define it once in a function and call it whenever needed.

In Kotlin, you declare a function using the fun keyword, followed by the function name and parentheses:

fun greet() {
    println("Hello!")
}

fun main() {
    greet()
    greet()
}
// Output:
// Hello!
// Hello!

The function greet contains one line of code, but we can call it as many times as we want. The code inside the function only runs when we call it by writing its name followed by parentheses.

Functions help organize your code into logical pieces. Each function should do one specific thing, making your program easier to read and maintain. You've actually been using a function all along: main() is the special function where your program starts executing.

challenge icon

Challenge

Medium

Declare a function called printWelcome that prints the following two lines when called:

Welcome to Kotlin!
Let's learn functions.

In your main function, call printWelcome exactly once.

Try it yourself

// TODO: Declare your printWelcome function here


fun main() {
    // TODO: Call the printWelcome function here
    
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground