- scala> class Phonebook {
- | val numbers = scala.collection.mutable.Map[String,String]()
- | def apply(name:String):String = numbers(name)
- | def update(name:String, number:String) = numbers(name) = number
- | }
- defined class Phonebook
- scala> val book = new Phonebook()
- book: Phonebook = Phonebook@1e406b09
- scala> book("jesse") = "123 456 7890"
- scala> println (book("jesse"))
- 123 456 7890
As you can see you can invoke the apply method in a similar way that [] are used on arrays in Java. When you call '
obj(param)
' the call is translated by the compiler to: 'obj.apply(param)
'. As such apply can have any number of arguments.Similarly '
obj(param) = value
' is compiled to 'obj.update(param,value)
'. Again the update method can have as many arguments as you wish. However only the last argument is treated as a value. So:- scala> class Echo {
- | def update(n:String, n2:String, n3:String ) = println(n,n2,n3)
- | }
- defined class Echo
- scala> val e = new Echo()
- e: Echo = Echo@2fa847df
- scala> e("hello", "hi") = "bonjour"
- (hello,hi,bonjour)
- scala> e("hello") = ("salut","bonjour")
:7: error: wrong number of arguments for method update: (String,String,String)Unit - e("hello") = ("salut","bonjour")
- ^
This makes sense because if apply has many arguments representing the key then the same key must work for the update method for assignment. If you have many values to assign try:
- scala> class Phonebook {
- | val numbers = scala.collection.mutable.Map[String, (Int, Int)]()
- | def apply(name:String) = numbers(name)
- | def update(name:String, number:(Int,Int)) = numbers(name) = number
- | }
- defined class Phonebook
- scala> val book2 = new Phonebook()
- book2: Phonebook = Phonebook@7a120cb3
- scala> book2("jesse") = (123, 4567890)
- scala> val (areaCode, local) = book2("jesse")
- areaCode: Int = 123
- local: Int = 4567890
No comments:
Post a Comment