Map with custom key in Scala

2019-08-28 20:25发布

问题:

There is a string representation of some data:

"jsonData": {
      "data1": {
        "field1": "data1",
        "field2": 1.0,
        "field3": true
      },
      "data211": {
        "field1": "data211",
        "field2": 4343.0,
        "field3": false
      },
      "data344": {
        "field1": "data344",
        "field2": 436778.51,
        "field3": true
      },
      "data41": {
        "field1": "data41",
        "field2": 14348.0,
        "field3": true
      }
    }

How do I represent it in Scala? I thought I could be either

Map[(String, Double, Boolean), String]

or

type KeyValueType = (String, Double, Boolean)
Map[KeyValueType, String]

But nevertheless, it gave me the errro:

error: missing arguments for method apply in class GenMapFactory;
follow this method with `_' if you want to treat it as a partially applied function

and also, I'm unsure it if would be the right representation.

So how do I represent it and, if my approach is right, how do I get rid of the error?

回答1:

Regarding your error, you probably just need to add () to invoke the apply method, since just an object name (Map) with type parameters is meaningless.

I would advise against using tuples to hold your data. They are over-used by beginners. Use a class instead. Something like

case class MyDataType(field1: String, field2: Double, field3: Boolean)

Then you read you data into a Vector[MyDataType].



标签: scala