Skip to content
AgileLogics
3 min read

Default and Named Parameters

Prerequisites: Methods

def connect(host: String, port: Int = 443, secure: Boolean = true): String =
  val scheme = if secure then "https" else "http"
  s"$scheme://$host:$port"

@main def params(): Unit =
  println(connect("example.com"))
  println(connect("example.com", 8443))
  println(connect("localhost", secure = false, port = 8080))
https://example.com:443
https://example.com:8443
http://localhost:8080
  • Default values (port: Int = 443) are used when an argument is left out, so one method covers many cases without overloads.
  • Named arguments (secure = false) can be given in any order and make calls self-documenting — especially for Boolean arguments, where connect("localhost", 8080, false) says little.

Varargs

A * after the type accepts any number of arguments:

def total(prices: Double*): Double = prices.sum

@main def varargs(): Unit =
  println(total(1.5, 2.5, 3.0))
  println(total())
  val basket = List(4.0, 6.0)
  println(total(basket*))
7.0
0.0
10.0

Inside the method, prices is a sequence. Pass an existing collection with basket*.