Scala create group of elements

倖福魔咒の 提交于 2019-12-02 23:48:49

问题


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.



来源:https://stackoverflow.com/questions/45763023/scala-create-group-of-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!