Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip optional parameters in Scala?

Tags:

scala

Given the following function with optional parameters:

def foo(a:Int = 1, b:Int = 2, c:Int = 3) ...

I want to keep the default value of a but pass new values to b and c only by positional assignment (rather than by a named assignment), that is any of the following syntaxes would be nice:

foo( , 5, 7)
foo(_, 5, 7)

Is something like that possible with Scala?

like image 242
cubic lettuce Avatar asked Oct 28 '15 22:10

cubic lettuce


3 Answers

There's no way to skip the parameters, but you can use named parameters when you call your foo method, for example:

// Call foo with b = 5, c = 7 and the default value for a
foo(b = 5, c = 7)

edit - You asked specifically how to do this by positional assignment: this is not possible in Scala.

like image 131
Jesper Avatar answered Nov 12 '22 07:11

Jesper


You can create another function, with one of the parameters applied.

def long(a: Int = 1, b: Int = 2, c: Int = 3) = a + b + c

def short(x: Int, y: Int) = long(b = x, c = y)

val s = short(10, 20) // s: Int = 31
like image 4
kukido Avatar answered Nov 12 '22 05:11

kukido


A solution (far from pretty) could be Currying

You would need to change the method signature a little bit:

// Just for "a" parameter

def foo(a: Int = 1)(b: Int = 2, c: Int = 3)

foo()(2,3)   // 6
foo(1)(2,3)  // 6
foo(2)(2,3)  // 7

For all the parameters:

def foo(a: Int = 1)(b: Int = 2)(c: Int = 3) = a + b + c

foo()()(3)   // 6
foo()(2)(3)  // 6
foo(2)()(3)  // 7
foo(3)()(3)  // 8
like image 1
Onilton Maciel Avatar answered Nov 12 '22 07:11

Onilton Maciel