Search code examples
scalafunctional-programmingtype-parameter

how to set default values for function parameters in scala


I am trying to set a default value (x) => x for the parameter keyFunction in the following function:

def count[A, B](list: List[A], keyFunction: (A) => B, isRatio : Boolean = false): Map[B, Double] = {
    lazy val number = list.size.toDouble
    list.groupBy(keyFunction).map{
      case (key, group) => if (isRatio) (key, group.size/number) else (key, group.size.toDouble)
    }
  }

I know a dumb solution is just to define another function:

  def simplyCount[A] (list: List[A], isRatio: Boolean = false): Map[A, Double] = count(list, (e: A) => e, isRatio)

How can I do it in a better way? Thanks in advance.


Solution

  • You can add the default argument as (x: A) => x, but you'll have to separate it into a separate parameter list if you want Scala to automatically infer the type only given the list:

    def count[A, B](list: List[A])(keyFunction: (A) => B = (x: A) => x, isRatio: Boolean = false): Map[B, Double] {
      ???
    }
    
    count(List("a", "B", "a", "c"))()
    // Map(a -> 2.0, c -> 1.0, B -> 1.0)
    

    You can do it as one parameter list, but you'll have to explicitly give it the type since the type inference won't be able to figure it out:

    def count[A, B](list: List[A], keyFunction: (A) => B = (x: A) => x, isRatio: Boolean = false): Map[B, Double] {
      ???
    }
    
    count[String,String](List("a", "B", "a", "c"))
    // Map(a -> 2.0, c -> 1.0, B -> 1.0)