Implicits, pimpl template, etc.

Say 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 Cimplicitly and without using aand bimplicit vals? That is, if I have a method that expects C:

def foo(c: C)
+3
source share
1 answer

Designation case class Ais out of date. You must use case class A(), otherwise assigning Ato val awill result in a Arelated object of the case class Athat is created behind the scene.

In my understanding, you wanted to Arefer to an instance of the case class, not a companion object.

, , , - A b , :

implicit def obtainC = new C(a, b)

implicit c foo:

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
+6

Source: https://habr.com/ru/post/1794122/


All Articles