WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Kotlin · Basic · question 17 of 100

What is the difference between a function and a method in Kotlin?

📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

In Kotlin, both functions and methods have similar syntax and purpose, they are used to define a block of code that performs a specific task. However, there is a key difference between the two.

A function is a standalone block of code that can be called from anywhere within the program. Functions in Kotlin are defined outside of any class definition, typically placed at the top level of a file, or within a companion object.

Here is an example of a simple function definition:

fun addNumbers(a:Int, b:Int): Int {
    return a+b
}

This function takes two arguments ‘a‘ and ‘b‘ and returns their sum. The function can be called from anywhere in the program:

val result = addNumbers(5,6)
println(result) // Output: 11

On the other hand, a method is a function that is defined inside a class. Unlike a standalone function, a method is called on an instance of the class, and can access the instance’s properties and methods.

Here is an example of a simple method definition:

class Calculator {
    fun addNumbers(a:Int, b:Int): Int {
        return a+b
    }
}

This method is defined within the ‘Calculator‘ class. It takes two arguments ‘a‘ and ‘b‘ and returns their sum. To call this method, we first need to create an instance of the ‘Calculator‘ class:

val calculator = Calculator()
val result = calculator.addNumbers(5,6)
println(result) // Output: 11

In summary, the main difference between functions and methods in Kotlin is that functions are standalone blocks of code that can be called from anywhere in the program, whereas methods are functions that are defined inside a class and are called on an instance of that class.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Kotlin interview — then scores it.
📞 Practice Kotlin — free 15 min
📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

All 100 Kotlin questions · All topics