[英]Is it possible to have a sub-trait inheirit a class parameter from another trait?
I am trying to DRY up my code a little bit.我正在尝试稍微整理一下我的代码。 I am using Circe to do some decoding.我正在使用 Circe 进行一些解码。 I have several classes and all of them have the form of:我有几个班级,所有班级都具有以下形式:
import io.circe.derivation.deriveDecoder
import io.circe.derivation.renaming.snakeCase
import io.circe.parser.decode
import io.circe.{Decoder, Error}
// Getter[A] just defines some functions for getting the data from an endpoint.
class JSONGetter extends Getter[MyClass] {
implicit val decoder: Decoder[MyClass] = deriveDecoder[MyClass](io.circle.derivation.renaming.snakeCase)
// .. other parsing code here
}
I would like to stop repeating myself with the implicit so I set out to make a new trait:我不想用隐含的方式重复自己,所以我开始创造一个新的特征:
trait JsonDecoding[A] {
implicit val decoder: Decoder[A] = deriveDecoder[A](io.circle.derivation.renaming.snakeCase)
}
So that I could shorten my class to:这样我就可以将课程缩短为:
class JSONGetter extends Getter[MyClass] with JsonDecoding[MyClass] {
// .. other parsing code here
}
This would be very convenient.这样会很方便。 However, I get A is not a class
when attempting to compile.但是,我在尝试编译时发现A is not a class
。 I think that I cannot do this the way I want to here.我认为我不能以我想要的方式来做这件事。
Is there a smart way to do this so I can not repeat myself when defining the implicit decoder that only changes in the class being decoded?有没有一种聪明的方法可以做到这一点,所以在定义仅在被解码的类中发生变化的隐式解码器时我不能重复自己?
You can use automatic derivation您可以使用自动推导
import io.circe.generic.auto._
case class Person(name: String)
instead of semi-automatic derivation而不是 半自动推导
io.circe.generic.semiauto
case class Person(name: String)
object Person {
implicit val fooDecoder: Person[Foo] = semiauto.deriveDecoder
implicit val fooEncoder: Person[Foo] = semiauto.deriveEncoder
}
or macro annotation @JsonCodec to simplify semi-automatic derivation或宏注解@JsonCodec简化半自动推导
import io.circe.generic.JsonCodec
@JsonCodec case class Person(name: String)
Let's assume that you prefer semi-automatic derivation rather than automatic one.假设您更喜欢半自动推导而不是自动推导。
Extending a trait is an incorrect way扩展特征是一种错误的方式
class JSONGetter extends Getter[MyClass] with JsonDecoding[MyClass] {
// ...
}
The thing is that deriveDecoder
is a macro and it's important that the macro is expanded in a proper place.问题是deriveDecoder
是一个宏,并且在适当的位置扩展宏很重要。 If you extend a trait and put implicit there then the macro is expanded in incorrect place.如果您扩展一个特征并将其隐式放置在那里,则宏会在不正确的位置展开。
You can define your own macro annotation that will add necessary implicit您可以定义自己的 宏注释,以添加必要的隐式
@jsonDecoding
class JSONGetter extends Getter[MyClass]
import scala.annotation.{StaticAnnotation, compileTimeOnly}
import scala.language.experimental.macros
import scala.reflect.macros.blackbox
@compileTimeOnly("enable macro paradise to expand macro annotations")
class jsonDecoding extends StaticAnnotation {
def macroTransform(annottees: Any*): Any = macro jsonDecodingMacro.impl
}
object jsonDecodingMacro {
def impl(c: blackbox.Context)(annottees: c.Tree*): c.Tree = {
import c.universe._
annottees match {
case q"$mods class $tpname[..$tparams] $ctorMods(...$paramss) extends { ..$earlydefns } with ..$parents { $self => ..$stats }" :: tail =>
val tparamNames = tparams.map {
case q"$mods type $tpname[..$tparams] = $tpt" => tpname
}
q"""
$mods class $tpname[..$tparams] $ctorMods(...$paramss) extends { ..$earlydefns } with ..$parents { $self =>
..$stats
implicit val decoder: _root_.io.circe.Decoder[$tpname[..$tparamNames]] =
_root_.io.circe.derivation.deriveDecoder[$tpname[..$tparamNames]](_root_.io.circe.derivation.renaming.snakeCase)
}
..$tail
"""
// or should the implicit be added to companion object?
case q"$mods object $tname extends { ..$earlydefns } with ..$parents { $self => ..$body }" =>
// ...
case q"$mods trait $tpname[..$tparams] extends { ..$earlydefns } with ..$parents { $self => ..$stats }" =>
//...
}
}
}
Scala | 斯卡拉 | How can this code be put into a macro annotation? 如何将这段代码放入宏注释中?
How to reduce boilerplate code with Scala Macros in Scala 2? 如何在 Scala 2 中使用 Scala 宏减少样板代码?
Pass implicit parameter through multiple objects 通过多个对象传递隐式参数
Scala macro-based annotation reuse 基于 Scala 宏的注解重用
Similarly for Cats type classes you can use Kittens to derive the type classes either atomatically同样,对于Cats类型类,您可以使用Kittens以原子方式派生类型类
import cats.derived.auto.functor._
case class Cat[Food](food: Food, foods: List[Food])
or semi-automatically或半自动
import cats.derived.semiauto
case class Cat[Food](food: Food, foods: List[Food])
object Cat {
implicit val fc: Functor[Cat] = semiauto.functor
}
If you prefer semi-automatic derivation then you can use Katnip macro annotations rather than write necessary implicit semiauto.functor
for every class如果您更喜欢半自动推导,那么您可以使用Katnip宏注释,而不是为每个类编写必要的隐式semiauto.functor
import io.scalaland.catnip.Semi
@Semi(Functor) case class Cat[Food](food: Food, foods: List[Food])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.