Kotlin Iniciante

dlard707
12.1K views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

It's all about fun !

In Kotlin function are define by the keyword fun.

You can declare a function like this:

Function with parameters

Here is a function that accept one String parameter and return an Int:

Function with expression body:

For simple and concise functions that returns values, we can replace the block body (between curly braces) by an expression body, with a single =:

You also can omit the return type by writing:

fun hello(s: String) = "Hello, $s !"
Function with no return value (Equivalent to Java's void):

As any return type, Unit can be omitted:

fun printHello(s: String) {
    println("Hello, $s !")
}
Default and Named Arguments

In Java, it happens that you need to overload functions to handle multiple signature. To avoid breaking APIs you also end by calling a unique function with default arguments, like the following snippet:

public void Constructor(String arg1) {
 Constructor(arg1, null, null); 
}
public void Constructor(String arg1, String arg2) {
 Constructor(arg1, arg2, null); 
}
public void Constructor(String arg1, String arg2, String arg3) {
  // Computation Here
}

Kotlin allow you to write the same code more concisely:

fun Constructor(arg1 : String, arg2 : String? = null, arg3 : String? = null) {
// Computation Here
}

So, you'll be able to call the Constructor function with:

Constructor("abc")
Constructor("abc", "def")
Constructor("abc", "def", "hij")

As you may notice, this can be confusing, as the parameters all are strings, named arg... Kotlin provide a syntax helper that give you the ability to name arguments in the function call:

Constructor(arg1 = "abc")
Constructor(arg1 = "abc", arg2 = "def")
Constructor(arg1 = "abc", arg2 = "def", arg3 = "hij")

If you name one argument, you need to name all the others

Variable number of arguments

If you don't how much arguments will be passed to a function, you can use the vararg keyword. That allows you to define a variable number of parameters, with the same type.

You can also pass an array to a vararg argument, with the * notation.

Tips from documentation: Only one parameter may be marked as vararg. A function's parameter marked as vararg should be the last parameter

Infix notation

Infix notation allow you to simplify your code by calling function without . or (), like:

1 add 2

This was the basics about functions in Kotlin. Now we'll some really nice features.

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content