Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

parameters







Basic Parameters

  • Overview: Fundamental to defining functions, basic parameters are specified in the function definition and are required when calling the function.
  • Syntax:
    def functionName(param1: Type1, param2: Type2): ReturnType = {
      // Function body
    }
    
  • Example:
    def add(x: Int, y: Int): Int = x + y
    







Default Parameters

  • Overview: Default parameters allow functions to be called with fewer arguments than defined, by specifying default values.
  • Syntax:
    def functionName(param1: Type1 = defaultValue1): ReturnType = {
      // Function body
    }
    
  • Example:
    def log(message: String, level: String = "INFO"): Unit = println(s"[$level] $message")
    log("System starting")  // Uses the default level of INFO
    







Named Arguments

  • Overview: Named arguments enable the specification of arguments out of order by naming them directly in the function call.
  • Syntax:
    functionName(param1 = value1, param2 = value2)
    
  • Example:
    def printDetails(name: String, age: Int, country: String): Unit = {
      println(s"Name: $name, Age: $age, Country: $country")
    }
    printDetails(age = 30, name = "Alice", country = "Canada")
    







Variable Arguments (Varargs)

  • Overview: Variable arguments (varargs) allow functions to accept an arbitrary number of arguments of the same type.
  • Syntax:
    def functionName(args: Type*): ReturnType = {
      // Function body
    }
    
  • Example:
    def sum(numbers: Int*): Int = numbers.sum
    println(sum(1, 2, 3, 4))  // Outputs 10
    







Higher-Order Functions as Parameters

  • Overview: Functions can take other functions as parameters, allowing for powerful abstractions and operations.
  • Syntax:
    def functionName(f: (Type1, Type2) => ReturnType): ResultType = {
      // Function body
    }
    
  • Example:
    def applyOperation(a: Int, b: Int, operation: (Int, Int) => Int): Int = operation(a, b)
    println(applyOperation(5, 3, _ + _))  // Outputs 8
    







Best Practices

  • Use Default Parameters to Avoid Overloading: Instead of creating multiple overloaded methods, use default parameters to simplify the API.
  • Leverage Named Arguments for Clarity: Especially in functions with many parameters or boolean flags, named arguments can enhance readability.
  • Prefer Varargs for Flexible Argument Lists: When the number of arguments is not fixed, use varargs to make your functions more adaptable.