如何在scala中设置函数参数的默认值

时间:2015-03-10 04:06:25

标签: scala functional-programming type-parameter

我正在尝试设置默认值(x)=> x为以下函数中的参数keyFunction:

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)
    }
  }

我知道一个愚蠢的解决方案就是定义另一个函数:

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

我怎样才能以更好的方式做到这一点?提前谢谢。

1 个答案:

答案 0 :(得分:3)

您可以将默认参数添加为(x: A) => x,但如果您希望Scala仅在给定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)

你可以把它作为一个参数列表来做,但你必须明确地给它类型,因为类型推断将无法弄明白:

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)