deflog(message: String, level: String ="INFO") = println(s"$level: $message")log("System starting") // prints INFO: System startinglog("User not found", "WARNING") // prints WARNING: User not found
注意从Java代码中调用时,Scala中的默认参数则是必填的(非可选),如:
// Point.scalaclass Point(val x: Double =0, val y: Double =0)
// Main.javapublicclassMain {publicstaticvoidmain(String[] args) {Point point =newPoint(1); // does not compile }}
命名参数
当调用方法时,实际参数可以通过其对应的形式参数的名称来标记:
defprintName(first: String, last: String): Unit = { println(first +" "+ last)}printName("John", "Smith") // Prints "John Smith"printName(first ="John", last ="Smith") // Prints "John Smith"printName(last ="Smith", first ="John") // Prints "John Smith"