scala 案例类字段的简单迭代

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23128433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:11:55  来源:igfitidea点击:

Simple Iteration over case class fields

scalacase-class

提问by 212

I'm trying to write a generic method to iterate over a case class's fields :

我正在尝试编写一个通用方法来迭代案例类的字段:

case class PriceMove(price: Double, delta: Double)

case class PriceMove(price: Double, delta: Double)

def log(pm : PriceMove) { info("price -> " + price + " delta -> " + delta)}

def log(pm : PriceMove) { info("price -> " + price + " delta -> " + delta)}

I need to make logable to handle any case class. What needs to be the argument type for logto handle case classes only and the actual generic field iteration code?

我需要log能够处理任何案例类。什么需要是log仅处理案例类和实际通用字段迭代代码的参数类型?

回答by serejja

Okay, considering the two questions I attached to the question, here is what I'd use:

好的,考虑到我附在问题上的两个问题,这是我要使用的:

object Implicits {
  implicit class CaseClassToString(c: AnyRef) {
    def toStringWithFields: String = {
      val fields = (Map[String, Any]() /: c.getClass.getDeclaredFields) { (a, f) =>
        f.setAccessible(true)
        a + (f.getName -> f.get(c))
      }

      s"${c.getClass.getName}(${fields.mkString(", ")})"
    }
  }
}

case class PriceMove(price: Double, delta: Double)

object Test extends App {
  import Implicits._
  println(PriceMove(1.23, 2.56).toStringWithFields)
}

This produces:

这产生:

PriceMove(price -> 1.23, delta -> 2.56)

回答by Norbert Radyk

I'm afraid there is no easy way to achieve what you're after, as you can't easily get the field names from the case class as discussed here: Reflection on a Scala case classand Generic customisation of case class ToString.

恐怕没有简单的方法可以实现您所追求的目标,因为您无法轻松地从案例类中获取字段名称,如下所述:对 Scala 案例类的反射案例类 ToString 的通用定制

You can try using reflection (though you can guarantee the order of the fields) or tools.nsc.interpreter.ProductCompletion, but both solutions are significantly more complex then you'd really expect.

您可以尝试使用反射(尽管您可以保证字段的顺序)或tools.nsc.interpreter.ProductCompletion,但这两种解决方案都比您真正期望的要复杂得多。