Programming in Kotlin: Fundamentals

Aug 9 2022 · Kotlin 1.6, Android 12, IntelliJ IDEA CE 2022.1.3

Part 3: Functions & Nullability

22. Write Custom Functions

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 21. Challenge: Use Nullables Next episode: 23. Return Data From Functions

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You鈥檙e accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You鈥檙e accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

In the previous parts of the course, you had to copy and paste code which you used multiple times. If these are smaller bits of code, then it wasn鈥檛 that big of a deal, but if you had to copy large pieces of code and change them according to some parameters, then you鈥檙e in trouble.

fun printHello() {

}
println("Hello")
printHello()
fun printHello(name: String) {
  println("Hello $name")
}
printHello("Sam")
printHello("Chris")
fun printHello(name: String = "World") {
...
name = "Fela"
...
val mood = "Happy"
...
...
println(mood)
...
  val mood = "Happy" // Cannot be accessed outside this function
...
}
// Outside the function
//  println(mood) // would cause a compile-time error
fun printHello(name: String = "World", isVeteran: Boolean = false) {
    if (isVeteran) println("Hello $name! Thank you for your service.")
    else println("Hello $name")
}
printHello("Sam")
printHello(name = "Sam")
printHello(isVeteran = true)
printHello(name = "Sam", isVeteran = true)
printHello(isVeteran = true, name = "Sam")
printHello("Sam", isVeteran = true)