抹掉Scala的糖衣(14) -- Update Method

欢迎关注我的新博客地址:http://cuipengfei.me/

在Scala中,名字叫做update的方法是有特殊作用的。

比如:

1
2
3
val scores = new scala.collection.mutable.HashMap[String, Int]
scores("Bob") = 100
val bobsScore = scores("Bob")

以上三行代码,我们创建了一个可变的map来存储得分情况,然后我们记录了Bob的得分是100分,最后我们又把Bob的分数取出来了。

这三行代码看似平淡无奇,实则暗藏了一点点玄机。

第二行实际是调用了HashMap的update方法。

第三行实际是调用了HashMap的apply方法。

我们可以把上面的代码改写成下面的等价形式:

1
2
3
val scores = new scala.collection.mutable.HashMap[String, Int]
scores.update("Bob", 100)
val bobsScore = scores.apply("Bob”)

虽然等价,但是可读性却降低了一些。

apply方法我们之前讲过,就不再赘述。

update方法也不太复杂,它的规则就是:

1
x(y) = z

这样的代码会被编译为:

1
x.update(y, z)

这次博文名字虽然以抹掉糖衣开头,实则有点名不符实,因为这个语言特性过于简单,糖衣很薄,一抹就透。

这次的目的主要是介绍一个update方法的适用场景。

我们来看用来修改某个人地址的一段代码:

1
2
3
4
5
6
7
8
class AddressChanger {

  def update(name: String, age: Int, newAddress: String) = {
    println(s"changing address of $name, whose age is $age to $newAddress")
    //actually change the address
  }

}

我们可以这样来调用它:

1
2
val changer = new AddressChanger()
changer.update("xiao ming", 23, "beijing")

或者,我们也可以这样来调用它:

1
2
val addressOf = new AddressChanger()
addressOf(name = "xiao ming", age = 23) = "beijing"

这两段代码是等价的。

比较一下,前一种用法显得中规中矩,没什么特别好的,也没啥特大的毛病。

可是后一种用法就不同了,读起来很通顺,有读英语语句的感觉:把名字叫做小明,年龄23岁的人的地址改为北京。

如果再给AddressChanger加上一个apply方法,我们还可以写这样的代码:

1
val currentAddress = addressOf(name = "xiao ming", age = 23)

这样,读取和更新的代码都看起来非常自然。

如果我们把这两段代码连起来看:

1
2
val currentAddress = addressOf(name = "xiao ming", age = 23)
addressOf(name = "xiao ming", age = 23) = "beijing"

感觉甚好。

addressOf(name = “xiao ming”, age = 23)可以看做一个整体,它就如同一个可读可写的属性。

我们把它放到赋值语句的右侧,就能取到小明的当前住址。

我们把它放到赋值语句的左侧,就能修改小明的住址。

apply和update都是蛮简单的语言特性,但是加以合适的应用,却能得到可读性极强的代码。

抹掉Scala的糖衣(14) -- Update Method,布布扣,bubuko.com

时间: 2024-08-12 18:29:42

抹掉Scala的糖衣(14) -- Update Method的相关文章

scala学习手记14 - 单例对象

java中的单例模式都很熟悉了:简单地说就是一个类只能有一个实例.在scala中创建单例对象非常简单,创建类时使用object关键字替换class即可.因为单例类无法初始化,所以不能向它的主构造函数传递参数. 下面是一个单例的示例: class Marker(val color: String) { println("Creating " + this) override def toString(): String = "marker color " + colo

Scala学习笔记-14

package com.leegh.function /** * @author Guohui Li */object PartiaAppliedFunction { def main(args: Array[String]): Unit = { val data = List(1, 2, 3, 4, 5, 6) /*data.foreach(println _) data.foreach { x => println(x) } def sum(a: Int, b: Int, c: Int) =

Scala 趣题 14 当自己调自己的时候

真是无奇不有, 下面的两个println语句哪个抛空指针,那个输出8 ?   val s1: String = s1   println(s1.length)   val s2: String = s2 + s2   println(s2.length) 解释: String类型默认被初始化成nulll null引用出现在字符串的位置按照语言规范默认被转化成字符串"null" Explanation The definitions of the values s1 and s2 are

scala 学习之三 Function 和 Method

scala 定义函数的关键字是 val 定义函数的通用格式是  val  函数名 = (参数列表)=> {函数体} object FunctionDemo { //通用的定义格式 val f1 = (x: Int, y: Int) => { x + y } //先定义函数的参数列表类型,具体的函数参数在函数体中定义 val f2: (Int, Int, Int) => Int = { (x, y, z) => { x + y + z } } def main(args: Array

How do I iterate over a Scala List (or more generally, a sequence) using theforeach method or for loop?

Scala List/sequence FAQ: How do I iterate over a Scala List (or more generally, a sequence) using theforeach method or for loop? There are a number of ways to iterate over a Scala List using theforeach method (which is available to Scala sequences li

Spring ’14 Wave Update: Installing Dynamics CRM on Tablets for Windows 8.1

One of the added bonuses of Dynamics CRM is its ability go where you go! With the Spring ’14 Wave Update, you can now download CRM to your tablet with Windows 8.1. If you currently have the CRM for tablets installed, make sure to uninstall it before

scala 基本语法_2

[[email protected] test]# scala Welcome to Scala version 2.9.3 (Java HotSpot(TM) Client VM, Java 1.7.0_67). Type in expressions to have them evaluated. Type :help for more information. scala> val oneHalf = new Rational(1, 2); <console>:7: error:

Beginning Scala study note(8) Scala Type System

1. Unified Type System Scala has a unified type system, enclosed by the type Any at the top of the hierarchy and the type Nothing at the bottom of the hierarchy. All Scala types inherit from Any. # Using Any, Book extends AnyRef, and x is an Int that

MongoDB - MongoDB CRUD Operations, Update Documents

Update Methods MongoDB provides the following methods for updating documents in a collection: Method Description  db.collection.updateOne() Updates at most a single document that match a specified filter even though multiple documents may match the s