fun
declares a function or a method.
Like variables, the return type comes after the function declaration.
C#
int Add(int a, int b)
{
return a + b;
}
Kotlin
fun add(a: Int, b: Int): Int {
return a + b
}
The return type Unit
is equivalent to void
in C# (and can be omitted).
C#
void DoWork()
{
//...
}
Kotlin
fun doWork(): Unit {
//...
}
// or
fun doWork() {
//...
}
Like C#, one-line methods can be reduced to an expression body.
C#
int Add(int a, int b) => a + b;
Kotlin
fun add(a: Int, b: Int): Int = a + b
For expression-body methods, the return type can be omitted and inferred.
Kotlin
fun add(a: Int, b: Int) = a + b