Leverage Kotlin Functions & Lambdas

May 22 2024 · Kotlin 1.9.24, Android 14, Kotlin Playground

Lesson 02: Understand Function Parameters

Demo

Episode complete

Play next episode

Next

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re 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 this lesson, you’ll see how to pass parameters to a function to make the function reusable with different arguments.

fun greetings(name: String, favLanguage: String) {
  println("Hello! I am $name. My favorite language is $favLanguage.")
}
fun main() {
  greetings("Bilbo", "Kotlin")
}

Named Arguments

Recently I moved to a house close to a road used by heavy trucks. This afternoon so many trucks were passing. I was distracted just a bit and wrote the following code:

fun main() {
  greetings("Kotlin", "Bilbo")
}
fun main() {
  greetings(favLanguage = "Kotlin", name = "Bilbo")
}

Default Arguments

Function parameters can have default values. For example, you can pass Kotlin as the default value of the favLanguage parameter:

fun greetings(name: String, favLanguage: String = "Kotlin") {
  println("Hello! I am $name. My favourite is language $favLanguage.")
}
fun main() {
  greetings(name = "Bilbo")
}
fun main() {
  greetings(name = "Bilbo", favLanguage = "Swift")
}

Returning Values

You’ve seen how to pass parameters to a function and used named and default arguments. Now, you’ll create a function that returns a value. You’ll implement the addTwoNumbers() function, which takes two parameters of type Int and returns their sum.

fun addTwoNumbers(num1: Int, num2: Int): Int {
  val sum = num1 + num2
  return sum
}
fun main() {
  val sumOfTwoNumbers = addTwoNumbers(7, 13)
  println("The sum is $sumOfTwoNumbers")
}
fun addTwoNumbers(num1: Int, num2: Int): Int = num1 + num2
import kotlin.math.sqrt

...

fun findSquareRoot(num: Float): Float {
  val squareRoot = sqrt(num)
  return squareRoot
}
fun main() {
  val squareRoot = findSquareRoot(576f)
  println("Square root => $squareRoot")
}
Square root => 24.0
fun main() {
  val squareRoot = findSquareRoot(729f)
  println("Square root => $squareRoot")
}
Square root => 27.0
fun findSquareRoot(num: Float): Float  = sqrt(num)
See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion