Named arguments work with function definitions. Parameters with defaults don't need to be given:

class my
    def f(i:Int = 2, j: Int) = i + j

var my = new my()

my.f(j = 1)        // i = 2, j = 1
my.f(i = 3, j = 1) // i = 3, j = 1
my.f(3, 1)         // i = 3, j = 1


This only works for methods (which are defined with def).

def func(i: Int = 2) = i

However, here is somewhat of a "hack" to do it regardless.


var f(i:Int=2,j:Int) => i + j

This does not work. If you want to define a lambda, try this

val f = (i:Int,j:Int) => i + j

This is the correct approach. Also you cannot assign default values in lambda. You need to define methods with def keyword. Try this:

def f(i:Int, j:Int=2) = i + j

Parameter with default value should be the last parameter because scala compiler will scan values from left-right. It'll only use default values if there are missing ones. In above code f(1) will produce 3 because j will use 2 as default value. So use the compulsory arguments in the left side and the ones with default values on right. Hope this helps

Explained here: In Scala, can you make an anonymous function have a default argument?


You can use a curried function here

def sum1(a:Int=2)(b:Int) = a+b


Hope this answers your question.

Related Query

More Query from same tag