adrianfc
5/1/2020 - 8:52 AM

Functions

// Declare a function void with no arguments
fun hello() {
  println("Hello World")
}

hello()


// Declare a function that returns a String with no arguments
fun hello(): String  {
  return "Hello World")
}

println(hello())

// Declare a function that returns a String with arguments
fun hello(name: String): String  {
  return "Hello $name")
}

println(hello("Adrian"))

// Declare a function that returns a String with default argument
fun hello(name: String = "Rick"): String  {
  return "Hello $name")
}

// Adrian
println(hello("Adrian"))

// Rick
println(hello())

// Compact Functions
fun getDirtySensorReading() = 20

// fun shouldChangeWater(day: String, temperature: Int = 22, dirty: Int = 20): Boolean {
fun shouldChangeWater(day: String, temperature: Int = 22, dirty: Int = getDirtySensorReading()): Boolean {
  val isToHot = temperature > 30
  val isDirty = dirty > 30
  val isSunday = day == "Sunday"

  return when {
    isToHot(temperature) -> true
    isDirty(dirty) -> true
    isSunday(day) -> true
    else -> false
  }
}

fun isToHot(temperature:Int): Boolean = temperature > 30
fun isDirty(dirty: Int) = dirty > 30
fun isSunday(day: String) = day == "Sunday"