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

Lesson Complete

Play Next Lesson
Next
Save for later
About this episode
See versions
See forum comments
Cinema mode Mark as Complete Download course materials
Previous episode: 21. Challenge: Use Nullables Next episode: 23. Return Data From Functions

This video was last updated on Aug 9 2022

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.

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’t that big of a deal, but if you had to copy large pieces of code and change them according to some parameters, then you’re 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)