简体   繁体   中英

Treat scala function with default parameter type as if it did not have default parameters

Disclaimer: I'm new to 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. Is there a way to treat recordHash as type 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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