scalacode
scalacode

Reputation: 1106

define list from val in object

I wrote this:

    def fields(): List[String] = List(Fields.ZONE, Fields.API, Fields.LOCATION, Fields.FACTORY)

  object Fields {
    val ZONE: String = "Zone"
    val API: String = "API"
    val LOCATION: String = "location"
    val FACTORY: String = "factory"
  }

I want to find an intelligent way to define List in def fields without typing manually all constants wrapped in the Fields object. Any suggestions, please.

Best regards

Upvotes: 2

Views: 100

Answers (1)

Tim
Tim

Reputation: 27356

This is one way to do it

case class FieldNames(
  ZONE: String = "Zone",
  API: String = "API",
  LOCATION: String = "location",
  FACTORY: String = "factory",
)
object Fields extends FieldNames

def fields(): List[String] = Fields.productIterator.map(_.toString).toList

This uses the fact that a case class implements Product which allows you to enumerate the fields in the class.

Note that it would be more usual to omit the () and make fields a val:

val fields: List[String] = Fields.productIterator.map(_.toString).toList

Upvotes: 3

Related Questions