[英]Treat scala function with default parameter type as if it did not have default parameters
Disclaimer: I'm new to Scala. 免责声明:我是Scala的新手。
I want to pass a function with default parameters as if its type did not have default parameters 我想传递带有默认参数的函数,就像其类型没有默认参数一样
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)
}
Here's the error I'm getting at compile time: 这是我在编译时遇到的错误:
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 = {
Intuitively, I think of recordHash
as type Record => Int
when the default parameter attributes
is not provided. 直观地,当未提供默认参数
attributes
时,我认为recordHash
为Record => Int
类型。 Is there a way to treat recordHash
as type Record => Int
? 有没有一种方法可以将
recordHash
视为Record => Int
类型?
I can't compile your code because I miss some types, but I think this will work. 我无法编译您的代码,因为我错过了一些类型,但是我认为这可以工作。
def dropDuplicates(dataset: Dataset, keyF: Record => Any = recordHash(_)) : Dataset = {
// keep only distinct records as defined by the key function
}
This works because recordHash(_)
is equivalent to x => recordHash(x)
, this way x
(the input of the function) is Record
which is the type you wanted. 之所以
recordHash(_)
是因为recordHash(_)
等效于x => recordHash(x)
,这样, x
(函数的输入)就是Record
,它就是您想要的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.