简体   繁体   English

Scala案例类和构造函数

[英]Scala case classes and constructors

I'm finding myself writing a lot of (sort of) boilerplate code. 我发现自己写了很多(某种)样板代码。 For example say I have the following traits 例如,说我有以下特征

trait Foo {
  def x: Int
}

trait Bar {
  def y: Boolean
  def z: String
}

Then I want a case class that does no more or less than implement these. 然后我想要一个不多于或少于实现这些的案例类。

case class MyClass(x: Int, y: Boolean, z: String) extends Foo with Bar

This doesn't seem annoying, but now imagine that my traits have a dozen def s each and that the names x , y , and z are much longer. 这似乎并不令人烦恼,但现在想象我的特征每个都有十几个def ,并且名称xyz要长得多。 Writing the case class out means I have to rewrite all of these as arguments of MyClass . 编写案例类意味着我必须将所有这些重写为MyClass参数。

Is there a way to generate the x: Int, y: Boolean, z: String constructor part automatically based on the traits I extend? 有没有办法根据我扩展的特征自动生成x: Int, y: Boolean, z: String构造函数部分?

I think what you are looking for is an annotation macro that can handle this work for you. 我认为你正在寻找的是一个可以为你处理这项工作的注释宏 You would then invoke this macro by writing something like this: 然后,您可以通过编写以下内容来调用此宏:

@FieldsFromTraits
case class MyClass extends Foo with Bar

Annotation macros can then rewrite your case class with information from the traits. 然后,注释宏可以使用来自特征的信息重写您的案例类。

A library that does something similar is MetaRest . 执行类似操作的库是MetaRest You might try to adapt that implementation. 您可能会尝试调整该实现。 I'll see if I can't put something together tonight. 我明白今晚是不是能把东西放在一起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM