隐式、粉刺图案等

发布于 2024-10-18 20:08:35 字数 311 浏览 2 评论 0原文

假设我有这些类:

case class A()
case class B()
case class C(a: A, b: B)

和这些变量:

val a = A()
val b = B()

有没有办法隐式获取 C 的实例,而不需要创建 ab隐式值?即,如果我有一个需要 C 的方法:

def foo(c: C)

Let's say that I have these classes:

case class A()
case class B()
case class C(a: A, b: B)

and these variables:

val a = A()
val b = B()

Is there a way to get an instance of C implicitly and without making a and b implicit vals? I.e. if I have a method expecting a C:

def foo(c: C)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

狂之美人 2024-10-25 20:08:35

case class A 表示法已被弃用。您必须使用 case class A(),否则将 A 分配给 val a 将导致 a 引用到在场景后面生成的案例类 A 的伴生对象。

据我了解,您希望 a 引用案例类的实例,而不是伴随对象。

如果是这样,您所要求的是可能的 - ab 不必是隐式的,但您必须在作用域中添加一个新的隐式方法:

implicit def obtainC = new C(a, b)

然后,您必须将 implicit 修饰符添加到方法 foo 中的 c

def foo(implicit c: C)

完成会话:

scala> case class A()
defined class A

scala> case class B()
defined class B

scala> case class C(a: A, b: B)
defined class C

scala> val a = A()
a: A = A()

scala> val b = B()
b: B = B()

scala> implicit def obtainC = new C(a, b)
obtainC: C

scala> def foo(implicit c: C) = {}
foo: (implicit c: C)Unit

scala> foo

The case class A notation was deprecated. You have to use case class A(), otherwise assigning A to the val a will result in a referring to the companion object of the case class A which is generated behind the scene.

It's my understanding you wanted a to refer to the instance of the case class, not the companion object.

If so, what you're asking is possible - a and b don't have to be implicit, but you do have to add a new implicit method into the scope:

implicit def obtainC = new C(a, b)

Then, you have to put the implicit modifier to c in the method foo:

def foo(implicit c: C)

Complete session:

scala> case class A()
defined class A

scala> case class B()
defined class B

scala> case class C(a: A, b: B)
defined class C

scala> val a = A()
a: A = A()

scala> val b = B()
b: B = B()

scala> implicit def obtainC = new C(a, b)
obtainC: C

scala> def foo(implicit c: C) = {}
foo: (implicit c: C)Unit

scala> foo
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文