想象一下以下(伪)类:
class Board(rows: Int, cols: Int)
{
val fields = Map[(Int, Int), Field] // Position is a tuple
def getField(position: (Int, Int)): Field
{
fields(position)
}
}
我怎么能这样做?我可以创建一个类型:
type Position = (Int, Int)
然后val fields = Map[Position, Field]
这可行吗?
答案 0 :(得分:1)
您的代码有语法错误,但一旦修复它们就应该有效。使用String
代替Field
(因为我不知道Field的定义),您可以在Scala REPL中编写它并看到它有效:
scala> val fields: Map[(Int, Int), String] = Map((1,2) -> "a", (3,4) -> "b")
fields: Map[(Int, Int),String] = Map((1,2) -> a, (3,4) -> b)
scala> def getField(position: (Int, Int)) = fields(position)
getField: (position: (Int, Int))String
scala> getField((1,2))
res1: String = a