试图弄清楚如何在类上重载括号.
我有这个代码:
class App(values: Map[String,String])
{
// do stuff
}
Run Code Online (Sandbox Code Playgroud)
我希望能够以这种方式访问值Map:
var a = new App(Map("1" -> "2"))
a("1") // same as a.values("1")
Run Code Online (Sandbox Code Playgroud)
这可能吗?
sep*_*p2k 20
您需要定义一个apply
方法.
class App(values: Map[String,String]) {
def apply(x:String) = values(x)
// ...
}
Run Code Online (Sandbox Code Playgroud)
为了完整起见,应该说你的"apply"可以采用多个值,而"update"作为"apply"的对偶,允许在赋值的左侧"括号重载"
Class PairMap[A, B, C]{
val contents: mutable.Map[(A,B), C] = new mutable.Map[(A, B), C]();
def apply(a:A, b:B):C = contents.get((a, b))
def update(a:A, b:B, c:C):Unit = contents.put((a, b), c)
}
val foo = new PairMap[String, Int, Int]()
foo("bar", 42) = 6
println(foo("bar", 42)) // prints 6
Run Code Online (Sandbox Code Playgroud)
所有这一切的主要价值在于它使人们不必为早期C系列语言中必须特殊的事物建议额外的语法(例如,数组元素赋值和获取).它对于伴随对象上的工厂方法也很方便.除此之外,应该注意,因为它是容易使您的代码过于紧凑而无法实际读取的事情之一.
正如其他人已经指出的那样,你想要超载apply
:
class App(values: Map[String,String]) {
def apply(s: String) = values(s)
}
Run Code Online (Sandbox Code Playgroud)
当你在它时,你可能想要重载伴侣对象也适用:
object App {
def apply(m: Map[String,String]) = new App(m)
}
Run Code Online (Sandbox Code Playgroud)
然后你可以:
scala> App(Map("1" -> "2")) // Didn't need to call new!
res0: App = App@5c66b06b
scala> res0("1")
res1: String = 2
Run Code Online (Sandbox Code Playgroud)
虽然这是好处还是混乱取决于你想要做什么.