Programming in Kotlin: Fundamentals

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

Part 3: Functions & Nullability

23. Return Data From 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: 22. Write Custom Functions Next episode: 24. Challenge: Work with 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.

Sometimes, you might want a variable or constant to be a result of a computation. This computation might require different data and resources and doing this directly in a variable might not be possible. For this, you do this computation inside a function. But this time around a function that returns a value.

fun createRange(start: Int, end: Int): IntRange {
  return start..end
}
val closedRange = createRange(1, 10)

for (number in closedRange) print("$number \t")
println()
fun printRange(range: IntRange) {
  for (number in range) print("$number \t")
  println()
}
val closedRange = createRange(1, 10)
// New code below
printRange(closedRange)
fun createRange(start: Int, end: Int, isHalfOpen: Boolean = false): IntRange {
  if (isHalfOpen) {
    return start until end
  } else {
    return start..end
  }
}
fun createRange(start: Int, end: Int, isHalfOpen: Boolean = false): IntRange {
  return if (isHalfOpen) {
    start until end
  } else {
    start..end
  }
}
val halfOpenRange = createRange(5, 10, true)
printRange(halfOpenRange)
fun createRange(start: Int, end: Int, isHalfOpen: Boolean = false): IntRange = if (isHalfOpen) {
    start until end
  } else {
    start..end
  }
fun createRange(start: Int, end: Int, isHalfOpen: Boolean = false) = if (isHalfOpen) {
    start until end
  } else {
    start..end
  }
fun createRange(start: Char, end: Char, isHalfOpen: Boolean = false) = if (isHalfOpen) {
    start until end
  } else {
    start..end
  }
val charRange = createRange('A', 'Z')
printRange(charRange)
fun printRange(range: CharRange) {
  for (character in range) print("$character \t")
  println()
}