我有以下多載方法,輸入可以是 aOption[String]或Option[Seq[String]]:
def parse_emails(email: => Option[String]) : Seq[String] = {
email match {
case Some(e : String) if e.isEmpty() => null
case Some(e : String) => Seq(e)
case _ => null
}
}
def parse_emails(email: Option[Seq[String]]) : Seq[String] = {
email match {
case Some(e : Seq[String]) if e.isEmpty() => null
case Some(e : Seq[String]) => e
case _ => null
}
}
我想使用 Spark 中的這種方法,所以我嘗試將它們包裝為 udf:
def parse_emails_udf = udf(parse_emails _)
但我收到以下錯誤:
error: ambiguous reference to overloaded definition,
both method parse_emails of type (email: Option[Seq[String]])Seq[String]
and method parse_emails of type (email: => Option[String])Seq[String]
match expected type ?
def parse_emails_udf = udf(parse_emails _)
是否可以定義一個可以包裝兩種選擇的udf?
或者是否可以創建兩個具有相同名稱的 udf,每個都指向一個多載選項?我嘗試了以下方法,但引發了另一個錯誤:
def parse_emails_udf = udf(parse_emails _ : Option[Seq[String]])
error: type mismatch;
found : (email: Option[Seq[String]])Seq[String] <and> (email: => Option[String])Seq[String]
required: Option[Seq[String]]
def parse_emails_udf = udf(parse_emails _ : Option[Seq[String]])
uj5u.com熱心網友回復:
Option[String]并且Option[Seq[String]]具有相同的擦除Option,所以即使 Spark 支持 udf 多載它也不起作用。
您可以做的是創建一個接受任何內容的函式,然后匹配引數并處理不同的情況:
def parseEmails(arg: Option[AnyRef]) = arg match {
case Some(x) =>
x match {
case str: String =>
??? // todo
case s: Seq[String] =>
??? // todo
case _ =>
throw new IllegalArgumentException()
}
case None =>
??? // todo
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/486223.html
