salvob
salvob

Reputation: 1370

Collections in scala, how to get elements in map

From lift-json:

scala> val json = parse("""
         {
           "name": "joe",
           "addresses": {
             "address1": {
               "street": "Bulevard",
               "city": "Helsinki"
             },
             "address2": {
               "street": "Soho",
               "city": "London"
             }
           }
         }""")
scala> case class Address(street:String, city: String)
scala> case class PersonWithAddresses(name: String, addresses: Map[String, Address])
scala> val joe = json.extract[PersonWithAddresses]
res0: PersonWithAddresses("joe", Map("address1" -> Address("Bulevard", "Helsinki"),
                                     "address2" -> Address("Soho", "London")))

I want to access elements of joe. I want to know the Joe's address1 city for example. How?

Bonus Question: what if PersonWithAddresses was

case class PersonWithAddress(name:String, addresses: Map[String, List[Address]])

how would I extract the size of that list?

P.S. question: what's the difference between joe.addresses("address1").size() and joe.addresses.get("address1").size ?

Upvotes: 0

Views: 119

Answers (1)

Łukasz
Łukasz

Reputation: 8663

Your question has nothing really to do with json and lift itself. You already have your object, you just don't know how to use scala collections.

In case without list, you can get your city with:

@ joe.addresses("address1") 
res4: Address = Address("Bulevard", "Helsinki")
@ res4.city 
res5: String = "Helsinki"

or joe.addresses("address1").city for short.

In case of list

case class PersonWithAddress(name:String, addresses: Map[String, List[Address]])

you just call size on list.

joe.addresses("address1").size

As for a difference between these two:

@ res7.addresses("address1").size 
res8: Int = 1
@ res7.addresses.get("address1").size 
res9: Int = 1

There is a big difference, see what happens when you call get

@ res7.addresses.get("address1") 
res10: Option[List[Address]] = Some(List(Address("Bulevard", "Helsinki")))

It returns an Option which could be viewed as a collection of size 0 or 1. Checking its size is not what you want to do.

map.get("key")

returns an Option which is either Some(value) if value is present in map, or None if it's not

map("key") or desugared map.apply("key") returns the item associated with key or exception if element is not present in the map.

Upvotes: 3

Related Questions