如何在提取值时将参数注释为模式匹配中的隐式参数



我有一个类似的类

case class A(a: Int, b: String)

和一个函数

def f(a: Int)(implicit b: String) =???

有可能做这样的事情吗?

val a = A(11, "hello")
a match {
  case A(a, implicit b) => f(a)
}

如何在提取后不显式声明参数 b 的情况下使参数 b 隐式。

我不会担心隐式传递参数,因为您可以在这种特殊情况下轻松显式提供它:

case class A(a: Int, b: String)
def f(a: Int)(implicit b: String) =???
val a = A(11, "hello")
a match {
  case A(a, b) => f(a)(b)
}

如果必须隐式传递该值,则需要在作用域中声明该值。例如:

a match {
  case A(a, b) => {
    implicit val s = b
    f(a)
  }
}

此外,正如已经指出的,不要将implicit与通用类型一起使用。最好将其包装在另一个类中:

case class A(a: Int, b: String)
case class SomeCustomString(s: String)
def f(a: Int)(implicit b: SomeCustomString) =???
val a = A(11, "hello")
a match {
  case A(a, b) => {
    implicit val s = SomeCustomString(b)
    f(a)
  }
}

如果你能解释隐式参数的用例,我可以提供一个更好的例子。

更新:有一种方法可以做你想做的事情:

case class SomeCustomString(s: String)
case class A(a: Int, b: String) {
  implicit val s = SomeCustomString(b)
}
def f(a: Int)(implicit s: SomeCustomString) =???
val a = A(11, "hello")
import a._
f(a.a)

或者,如果您必须在模式匹配中拥有它,则最后一位将是:

a match {
  case x: A => {
    import x._
    f(x.a)
  }
}

更新 2:或者,作为另一种方法(再次,implicit在很大程度上是多余的(:

case class SomeCustomString(s: String)
case class A(a: Int, b: String) {
  implicit val s = SomeCustomString(b)
  def invokeF = f(a)
}
def f(a: Int)(implicit s: SomeCustomString) =???
val a = A(11, "hello")
a.invokeF

a match {
  case x: A => x.invokeF
}

这有帮助吗?

最新更新