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

时间:2018-03-13 20:03:14

标签: scala pattern-matching implicit

我有一个像

这样的课程
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。

1 个答案:

答案 0 :(得分:3)

我不担心隐式传递参数,因为在这种特殊情况下你可以很容易地明确地提供它:

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
}

这有帮助吗?