How to skip optional parameters in Scala?

前端 未结 3 1560
[愿得一人]
[愿得一人] 2021-02-19 03:30

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

相关标签:
3条回答
  • 2021-02-19 03:47

    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
    
    0 讨论(0)
  • 2021-02-19 03:56

    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
    
    0 讨论(0)
  • 2021-02-19 03:57

    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.

    0 讨论(0)
提交回复
热议问题