基本属性有 _= 语法。这大致是 Java 的 getter 和 setter 等价物。但是还有什么可以与 Java 的索引属性相媲美的吗?
我想让人们的生活更容易允许这样的事情:
环境:
titles.title(1) = "title of 1" // returns nothing
得到:
titles.title(1) // returns "title of 1"
Scala 有可能吗?
更新:示例代码
class Foo {
val title = new IndexedProperty[Int, String]
}
class IndexedProperty[A, B] {
var map = Map.empty[A, B]
def apply(key: A): Option[B] = map.get(key)
def update(key: A, value: Option[B]): Unit = {
value match {
case Some(v) => map += (key -> v)
case None if map.contains(key) => map -= key
case _ =>
}
}
}
val foo = new Foo
foo.title(1) = Some("Title of 1")
println(a.title(1)) // yields Some("Title of 1")
println(a.title(2)) // yields None