This is the seventh part of the video series on Kotlin language.
Read and watch the other parts here.
1. | Hello Kotlin |
2. | Declaring Variables |
3. | Data Types |
4. | String (Part 1) |
5. | String (Part 1) |
6. | Conditional Expressions |
We discuss writing functions in Kotlin language.
We’ve been writing a main function in all these examples. So that should have already given us some idea about the syntax of the functions. A Function is written using the fun keyword.
fun main(args:Array<String>){ println(sayHello("Sam")) } fun sayHello(name:String):String{ return "Hello $name" }
You can omit the return type of a function if doesn’t return anything.
fun print(message:String){ println(message) }
We can also make a function that does not return anything to return Unit, which means Nothing. Unit can be used in Generics, which we will discuss later.
fun printAgain(message:String):Unit{ println(message) }
Functions can be written as expressions, like our if-else and when-else constructs. An add function thats adds two numbers can be written as an expression like this.
//Normal function fun add(x:Int,y:Int):Int{ return x + y } //Expressions fun add(x:Int,y:Int) = x + y fun square(x:Int) = x * x }
You can find the video here.