Home » Blog » Default Parameter Values and Named Arguments

Default Parameter Values and Named Arguments

  1. A simple function that takes a parameter of type String and returns Unit (i.e., no return value).
  2. A function that takes a second optional parameter with default value Info. The return type is omitted, meaning that it’s actually Unit.
  3. A function that returns an integer.
  4. A single-expression function that returns an integer (inferred).
  5. Calls the first function with the argument Hello.
  6. Calls the function with two parameters, passing values for both of them.
  7. Calls the same function omitting the second one. The default value Info is used.
  8. Calls the same function using named argument and changing the order of the arguments.
  9. Prints the result of a function call.
fun printMsg(message: String): Unit 
{                               
    println(message)
}

fun printMsgWithPre(message: String, prefix: String = "Info") 
{  
    println("[$prefix] $message")
}

fun sum(x: Int, y: Int): Int 
{                                          
    return x + y
}

fun multiply(x: Int, y: Int) = x * y                                    

fun main() 
{
    printMsg("Hello")                                                                   
    printMsgWithPre("Hello", "Log")                              
    printMsgWithPre("Hello")                                     
    printMsgWithPre(prefix = "Log", message = "Hello")           
    println(sum(1, 2))                                                  
}

 

Leave a Reply

Your email address will not be published.