Reputation: 418
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)
}
Upvotes: 1
Views: 265
Reputation: 14825
Start parenthesis immediately after Map to tell scala compiler that parenthesis belongs to Map
Instead of this
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 }
}
do this
object UserRepository {
val users = Map( 1 -> User(1, "John", "Doe", 32, Some("male")),
2 -> User(2, "Johanna", "Doe", 30, None)) //start parenthesis after Map
//def findById(id: Int): Option[User] = users
//def findAll = users.values
def getUsers() = { users }
}
Upvotes: 2
Reputation: 170733
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)
)
Upvotes: 6