简体   繁体   English

将带有默认参数类型的scala函数视为没有默认参数

[英]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时,我认为recordHashRecord => 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM