DEV Community

loading...
Cover image for How to write functions in Kotlin? (Basic syntax)

How to write functions in Kotlin? (Basic syntax)

adrianbornea profile image Adrian Bornea ・1 min read

Functions are the building block of any programming language. They allow us to write DRY (Don't Repeat Yourself) code.

Let's continue our Kotlin tutorial by exploring the elements of a function.

We will start with a function that prints the current year. So it won't return anything.


fun printYear(): Unit {
println(2019)

}

Let's examine each part:

  1. fun - the keyword that tells us that we are about to write a function
  2. printYear() - the name of the function
  3. : Unit - the return type. Unit is the equivalent of void in Java.
  4. { } - the body of the function

NOTE: Unit is not required. Kotlin will allow us to write this function as:

fun printYear() {
println(2019)

}

Now let's write a basic function that generates a team name based on the names of the players that compose that team. For example, if the players are named Adrian and Jacob, the name of the team will be AdrianJacobTeam.

fun generateTeamName(firstName: String, secondName: String): String {
return firstName + secondName + "Team"
}

Let's see what we have in addition to the previous function:

  1. (firstName: String, secondName: String) - The parameters needed to call the function. We declare them without var or val.
  2. return firstName + secondName + "Team" - if our function is not void it will have to contain the return statement (same type as the one declared)

Actually there also other types of functions, but we will analyze them one at a time.

Photo by basitixustito

Discussion

pic
Editor guide