Scala create group of elements

2020-05-10 09:07发布

问题:

I want to create a group of elements in a message as in below image

Updated:

 case class Element(key:String;value:String)

Message can be represented something like below

 case class Msg(field1:Element,field2:Group)

Group->represents the repeating group - I need help to define group and sub groups

The element defines the key=value combination which is repeated in groups

The following are some points

  1. Are the "fields" attributes of a FixMessage?

    -Yes they are attributes of a Fix Message and each field is represented as case class Element(key:String;value:String)

  2. Repeating group they are Element repeating no of times

  3. Are the keys and values all Strings?

    -Consider them as string for now

  4. Field N (Field 1, Field 2, etc) represent different types?

    -Yes they represent it as different data types.But for now we can take them as of same data type to make it simple.

Output :

key2=value2 ;key3=value3;key4=value=4;key3=value3;key4=value=4;key2=valu‌​ e2;key3=value3;key‌​4=value4;key3=value‌​3;key4=value4

Explaination

The group key2=value2 is repeating 2 times The sub group is key3=value3;key4=value=4;key3=value3;key4=value=4 which is gain repeating 2 times in each group (key2=value2) respectively

回答1:

If I understand the domain correctly, something like this should work:

case class Message(entries: List[Entry])

case class Entry(name: String, value: Value)
trait Value
object Value {
  case class Single (v: String) extends Value
  case class Group (entries: List[List[Entry]]) extends Value
}

Message(
  Entry("Key 1", Value.Single("Value 1")),
  Entry("Key 2", Value.Group(
    List(
      List(
        Entry("Key 3", Value.Single("Value 3")),
        Entry("Key 4", Value.Single("Value 4"))
      ),
      List(
        Entry("Key 3", Value.Single("Value 5")),
        Entry("Key 4", Value.Single("Value 6"))
      )
    )
  ))
)

Of course some helper functions could be created to make a nicer DSL for it.