加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 18:37:22 所属栏目:安全 来源:网络整理
导读:我有一个类似的课程 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. 解决方法 我不担心隐
我有一个类似的课程

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.

解决方法

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

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

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

val a = A(11,b) => f(a)(b)
}

如果必须隐式传递值,则需要在范围内声明.例如:

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

另外,正如已经指出的那样,不要使用带有常见类型的隐式.如果你把它包装在另一个类中会更好:

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

case class SomeCustomString(s: String)

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

val a = A(11,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:或者,作为另一种方法(再次,隐含大部分冗余):

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
}

这有帮助吗?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读