Scala 案例类和构造函数 [英] Scala case classes and constructors

查看:47
本文介绍了Scala 案例类和构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己写了很多(某种)样板代码.例如说我有以下特征

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

这看起来并不烦人,但现在想象一下我的特征每个都有十几个 def 并且名称 x, y, 和 z 更长.写出案例类意味着我必须将所有这些重写为 MyClass 的参数.

This doesn't seem annoying, but now imagine that my traits have a dozen defs each and that the names x, y, and z are much longer. Writing the case class out means I have to rewrite all of these as arguments of MyClass.

有没有办法根据我扩展的特征自动生成 x: Int, y: Boolean, z: String 构造函数部分?

Is there a way to generate the x: Int, y: Boolean, z: String constructor part automatically based on the traits I extend?

推荐答案

我认为您正在寻找的是 注释宏 可以为您处理这项工作.然后,您将通过编写如下内容来调用此宏:

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.

有类似功能的库是 MetaRest.您可能会尝试调整该实现.我看看今晚能不能把东西放在一起.

A library that does something similar is MetaRest. You might try to adapt that implementation. I'll see if I can't put something together tonight.

这篇关于Scala 案例类和构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆