隐式、粉刺图案等
假设我有这些类:
case class A()
case class B()
case class C(a: A, b: B)
和这些变量:
val a = A()
val b = B()
有没有办法隐式获取 C
的实例,而不需要创建 a
和 b
隐式值?即,如果我有一个需要 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
case class A
表示法已被弃用。您必须使用case class A()
,否则将A
分配给val a
将导致a
引用到在场景后面生成的案例类A
的伴生对象。据我了解,您希望
a
引用案例类的实例,而不是伴随对象。如果是这样,您所要求的是可能的 -
a
和b
不必是隐式的,但您必须在作用域中添加一个新的隐式方法:然后,您必须将
implicit
修饰符添加到方法foo
中的c
:完成会话:
The
case class A
notation was deprecated. You have to usecase class A()
, otherwise assigningA
to theval a
will result ina
referring to the companion object of the case classA
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
andb
don't have to be implicit, but you do have to add a new implicit method into the scope:Then, you have to put the
implicit
modifier toc
in the methodfoo
:Complete session: