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()
I开发者_C百科s 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)
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
精彩评论