免责声明:我是Scala的新手。
我想传递一个带有默认参数的函数,就好像它的类型没有默认参数
一样import scala.util.hashing.MurmurHash3
type Record = Map[String, String]
type Dataset = Seq[Record]
def dropDuplicates(dataset: Dataset, keyF: Record => Any = recordHash) : Dataset = {
// keep only distinct records as defined by the key function
// removed method body for simplicity
return dataset
}
def recordHash(record: Record, attributes: Option[Seq[String]] = None) : Int = {
val values : Seq[String] = attributes
.getOrElse(record.keys.toSeq.sorted)
.map(attr => record(attr))
return MurmurHash3.seqHash(values)
}
这是我在编译时遇到的错误:
error: type mismatch;
[ant:scalac] found : (Record, Option[Seq[String]]) => Int
[ant:scalac] required: Record => Any
[ant:scalac] def dropDuplicates(dataset: Dataset, keyF: Record => Any = recordHash) : Dataset = {
直观地说,当未提供默认参数recordHash
时,我认为Record => Int
为attributes
类型。有没有办法将recordHash
视为Record => Int
类型?
答案 0 :(得分:2)
我无法编译你的代码,因为我错过了某些类型,但我认为这样可行。
def dropDuplicates(dataset: Dataset, keyF: Record => Any = recordHash(_)) : Dataset = {
// keep only distinct records as defined by the key function
}
这是有效的,因为recordHash(_)
等同于x => recordHash(x)
,这种方式x
(函数的输入)是Record
,这是您想要的类型。