尝试了解基本的Scala概念。为什么这段代码没有编译?
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)
}
错误:(25,42)值过滤器不是对象cala.collection.immutable.Map的成员 for((k,v)&lt; - UserRepository.getUsers()){
我预计val用户正在持有Map?
简单地图工作正常:
val simpleMap = Map (1 -> "First", 2 -> "Second")
for ((k,v) <- simpleMap ){
println(v)
}
答案 0 :(得分:5)
Route::post('posts', '....');
这是两个单独的表达式:首先执行val users = Map
( 1 -> User(1, "John", "Doe", 32, Some("male")),
2 -> User(2, "Johanna", "Doe", 30, None)
)
(在Scala中有效,并将类型为val users = Map
的伴随对象分配给Map
) ,然后评估
users
扔掉结果。如果您通过将( 1 -> User(1, "John", "Doe", 32, Some("male")),
2 -> User(2, "Johanna", "Doe", 30, None)
)
移到上面的行来告诉编译器定义尚未结束,那么它将起作用:
(
答案 1 :(得分:2)
在Map之后立即启动括号,告诉scala编译器该括号属于Map
而不是这个
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 }
}
这样做
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 }
}