Search code examples
scalascala-option

Scala: optional sequence of arguments


Here's some data:

val data = List(1,1,2,2,3)

I would like to write a function filteredSum which supports the following:

/*1*/ filteredSum(data) // Outputs 0
/*2*/ filteredSum(data, 1) // Outputs 1 + 1 = 2
/*3*/ filteredSum(data, 1, 3) // Outputs 1 + 1 + 3 = 5
/*4*/ filteredSum(data, None) // Outputs 1 + 1 + 2 + 2 + 3 = 9

There are a couple close misses; for instance * notation supports the first three calls:

def filteredSum(data: Seq[Int], filterValues: Int*): Int = {
  data.intersect(filterValues).sum
}

And options give you the fourth:

def filteredSum(data: Seq[Int], filterValues: Option[Seq[Int]]) : Int = {
  if(filterValues.nonempty) data.intersect(filterValues.get).sum
  else data.sum
}

But with this implementation the first three calls look a lot clunkier: filteredSum(data, Some(Seq(1))), for instance.

Any other ideas? (Obviously my actual use case is much more complicated than just adding some numbers together, so I'm not looking for answers that are too closely tied to the intersect or sum functions.)


Solution

  • Make two functions:

     def filteredSum(data: Seq[Int], filterValues: Int*): Int =  
       data.filter(filterValues.toSet).sum
    
    
     def filteredSum(data: Seq[Int], all: Boolean) : Int = 
       if(all) data.sum else 0