Function

fun greet() {
  println("Hey there!")
}
fun main() {
  //Function call
  greet() //Prints: Hey there!
}

Function Literals

fun main() {
  //Anonymous Function:
  var getProduct = fun(num1: Int, num2: Int): Int {
return num1 *num2
  }
  println(getProduct(8, 3))
  //Prints: 24
//Lambda Expression
  var getDifference = { num1: Int, num2: Int -> num1 -num2 }
  println(getDifference(10, 3))
  //Prints: 7
}

Single expression function

fun fullName(firstName: String, lastName: String) = "$firstName $lastName"
fun main() {
  println(fullName("Ariana", "Ortega"))
  //Prints: Ariana Ortega
  println(fullName("Kai", "Gittens"))
  //Prints: Kai Gittens
}

Return Statement

//Return type is declared outside the parentheses
fun getArea(length: Int, width: Int): Int {
  var area = length *width
  //return statement
  return area
}
fun main() {
  var myArea = getArea(10, 8)
println("The area is $myArea.")
//Prints: The area is 80.
}

Named Parameters

fun findMyAge(currentYear: Int, birthYear: Int) {
   var myAge = currentYear -birthYear
println("I am $myAge years old.")
}
fun main() {
  findMyAge(currentYear = 2020, birthYear = 1995)
  //Prints: I am 25 years old.
  findMyAge(birthYear = 1920, currentYear = 2020)
  //Prints: I am 100 years old.
}

Default Parameters

fun favoriteLanguage(name, language = "Kotlin") {
  println("Hello, $name. Your favorite programming language is $language")  
}
fun main() {
  favoriteLanguage("Manon") 
  //Prints: Hello, Manon. Your favorite programming language is Kotlin

  favoriteLanguage("Lee", "Java") 
  //Prints: Hello, Lee. Your favorite programming language is Java
}

Function Parameters

fun birthday(name: String, age: Int) {
   println("Happy birthday $name! You turn $age today!")
}
fun main() {
  birthday("Oscar", 26) 
  //Prints: Happy birthday Oscar! You turn 25 today!
  birthday("Amarah", 30) 
  //Prints: Happy birthday Amarah! You turn 30 today!
}
Comments