Functions
Kotlin
has a very powerful support for functional programming. Having that in mind, it is important to know functions really well ๐ and I guess that's why you're here.
Basicโ
How do I write a kotlin
function?
fun hello(){
println("Hello!")
}
- we use the
fun
keyword to declare a function, isn't it funny and fun ๐บ ๐ - this is followed by the
function name
which in this case ishello
- adding parenthesis
()
that will contian our parameters - finally adding braces
{}
for our function body
But what about using it?
hello()
> Hello!
Another thing, you've mention parameters in the info section there, what are they?
Parametersโ
Parameters are placeholders declared in a function, they don't have concrete values
Arguments on the other hand are now the actual values passed to a function when it is being used
Umm okay ๐คจ do you have an example?
fun markAsRead(book: String){ // book here is a PARAMETER
println("Hello $book!")
}
markAsRead("Kotlin") // "Kotlin" is an ARGUMENT
> Hello Kotlin!
book
is declared as a parameter (placeholder)"Kotlin"
is the argument for thebook
parameter- parameters are declared by specifiying the name of the parameter followed by the type
- you can declare more than one parameter for any function, just specify the name and type followed by a comma
What if I want to add more than one parameter?
fun hello(greeting: String, name: String){
println("$greeting $name!")
}
hello("Jambo", "Kotlin")
> Jambo Kotlin!
Usecasesโ
Functions are used everywhere in the kotlin language, an example is creating any list
fun main(){
val list = listOf(1,2,3)
println(list)
}
> [1,2,3]
In the example above, listOf
and println
are examples of Kotlin functions found in the standard library.
There's so much more you can learn about functions like named arguments and default values just to mention a few.