我有一个方法如下:
protected def extract(implicit params:Params) =
Map(
"address" -> params.address,
"city" -> reconcileCity,
"region" -> params.region,
)collect {
case (k, v) if v.isDefined => k -> v.get
}
我想用另一种方法替换城市的价值如下:
protected def reconcileCity(implicit params:Params)
params.city match {
case Some("madras") => "Chennai"
case Some("bangalore") => "Bengaluru"
case Some("gurgaon") => "Gurugram"
case _ => params.city.mkString
}
但我得到的错误如下:
Error:(177, 24) value isDefined is not a member of java.io.Serializable
case (k, v) if v.isDefined => k -> v.get
Error:(177, 44) value get is not a member of java.io.Serializable
case (k, v) if v.isDefined => k -> v.get
请帮忙。
答案 0 :(得分:0)
isDefined
是Option
类中存在的方法。
但是你试图用String替换Option [String],并在其上调用isDefined
。
我假设params
中的所有内容都是Option
,因此您的代码应如下所示:
protected def reconcileCity(implicit params:Params)
params.city match {
case Some("madras") => Some("Chennai")
case Some("bangalore") => Some("Bengaluru")
case Some("gurgaon") => Some("Gurugram")
case other => other
}
答案 1 :(得分:0)
同意@ Alexey的回答isDefined
和get
是可以应用于Option
类的方法。 Alexay建议将所有返回值更改为Some
,但我建议仅将返回值更改为Some
protected def extract(implicit params:Params) =
Map(
"address" -> params.address,
"city" -> Some(reconcileCity),
"region" -> params.region
)collect {
case (k, v) if v.isDefined => k -> v.get
}
protected def reconcileCity(implicit params:Params) = params.city.get match {
case "madras" | "Madras" => "Chennai"
case "bangalore" | "Banglore" => "Bengaluru"
case "gurgaon" | "GurGaon" => "Gurugram"
case _ => params.city.mkString
}