gpt4 book ai didi

Scala:如何检查是否至少定义了一个类的字段?

转载 作者:行者123 更新时间:2023-12-01 23:22:34 26 4
gpt4 key购买 nike

我有一个类,它有几个可选字段,如下所示:

class Container(f1: Option[String] = None,
f2: Option[Boolean] = None,
f3: Option[Int] = None,
f4: Option[String] = None
// ... 30 other fields which is unfortunate/terrible and
// cannot be changed at the moment
) {
def hasAtleastOneDefinedField: Boolean = {
this.f1.isDefined ||
this.f2.isDefined ||
this.f3.isDefined ||
this.f4.isDefined
// this is too-much of boilerplate
}

// This is something along the lines of what I want
def hasAtleastOneDefinedField2: Boolean = {
// this.getAllDeclaredFields.find(field => field.value.isDefined)
???
}
}

是否可以在不使用反射的情况下做同样的事情?

最佳答案

不确定这能为您节省多少,但是:

  val hasAtLeastOneDefinedField = List(f1, f2, f3, ..., f35).exists { _.isDefined }

不要认为除了反射/宏之外还有其他方法。

关于Scala:如何检查是否至少定义了一个类的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32084618/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com