Levijatanu Levijatanu - 2 months ago 6
Scala Question

Map containing Objects not workig as expected Scala

Trying to understand basic Scala concepts. Why is this code not compiling ?

case class User(
id: Int,
firstName: String,
lastName: String,
age: Int,
gender: Option[String])

object UserRepository {
val users = Map
( 1 -> User(1, "John", "Doe", 32, Some("male")),
2 -> User(2, "Johanna", "Doe", 30, None)
)
//def findById(id: Int): Option[User] = users
//def findAll = users.values
def getUsers() = { users }
}

for ((k,v) <- UserRepository.getUsers() ){
println(v)
}


Error:(25, 42) value filter is not a member of object cala.collection.immutable.Map
for ((k,v) <- UserRepository.getUsers() ){

I expected that val users is holding Map ?

Simple map is working fine:

val simpleMap = Map (1 -> "First", 2 -> "Second")

for ((k,v) <- simpleMap ){
println(v)
}

Answer
val users = Map
( 1 ->  User(1, "John", "Doe", 32, Some("male")),
  2 -> User(2, "Johanna", "Doe", 30, None)
)

This is two separate expressions: first you do val users = Map (which is valid in Scala, and assigns the companion object of type Map to users), then evaluate

( 1 ->  User(1, "John", "Doe", 32, Some("male")),
  2 -> User(2, "Johanna", "Doe", 30, None)
)

and throw away the result. If you tell the compiler the definition isn't over yet by moving ( to the line above, it'll work:

val users = Map(
  1 ->  User(1, "John", "Doe", 32, Some("male")),
  2 -> User(2, "Johanna", "Doe", 30, None)
)
Comments