circe automatic derivation - struggling with the imports
circe automatic derivation - struggling with the imports
I have a method exposed on my API that looks like this:
def read[T](implicit decoder: Decoder[T]): T
def read[T](implicit decoder: Decoder[T]): T
A user can bring along any T
they like and my code will attempt to parse the json result into a T
.
T
T
The issue I want to resolve is that any user must also import io.circe.generic.auto._
in order to get this to work and auto-derive the Decoder[T]
.
io.circe.generic.auto._
Decoder[T]
Is there any way I can change my API to avoid the user having to bring this import?
T
T
Decoder[T]
circe
import
Agree with @Tim, but would also like to note, that using
io.circe.generic.auto
may have cause weird side-effects: it generates Decoder[T] every time you try to resolve the implicit in a new scope, so you may end with a separate decoder instance for each method requiring implicit decoder: Decoder[T]
– shutty
Sep 16 '18 at 14:48
io.circe.generic.auto
implicit decoder: Decoder[T]
1 Answer
1
It could be if you do it in a library - implicits would easily conflict causing troubles for your users.
In Typelevel Scala 4 can use customizable imports - it didn't landed in Scala 2.12 but (after several iterations) landed on 2.13. You could recommend your users have some implicits always in scope this way once 2.13.0 is released, but that will be conscious decision on their part.
Hmm - your code doesn't appear to work (it doesn't compile). I did try exploring your idea of using a type alias, but I didn't come to anything. Yes this is for a common module/library shared between the application.
– Cheetah
Sep 15 '18 at 12:54
I guess you put type alias directly in the file, which Scala doesn't allow. Put it into package object and try to compile again.
– Mateusz Kubuszok
Sep 17 '18 at 7:46
Type alias was in a package object, the code you posted doesn't compile (nothing to do with the type alias, its the implicit that is defined)
– Cheetah
Sep 17 '18 at 8:07
I could have sworn it worked and I used it in my code, but apparently I was wrong. I edited the answer.
– Mateusz Kubuszok
Sep 17 '18 at 8:56
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Your description isn't quite correct. The user cannot bring any
T
, they can only bring aT
for which there is an implicit value of typeDecoder[T]
. It is important that the user is aware that this depends on thecirce
library, not your code, so it is good that they are required to have thatimport
.– Tim
Sep 13 '18 at 9:16