了解scala中的更新方法

时间:2017-06-13 09:34:21

标签: scala jvm

我可以理解scala中的switch (someInt) { case 1: // Validate if the form is filled correctly. // The event returns true if that is the case. bool? isValid = ValidateStuff?.Invoke(); if (isValid) // If passed validation go to next step in form GoToNextStep?.Invoke(); break; // There are more cases, but you get the point (...) } 方法,它主要是将函数应用于值。在许多情况下,它被用作构造函数的一种形式。

我们假设apply是地图。一个例子是list,它从列表中获取给定的元素。

我还发现了更新方法的例子

def apply(id : Int) = list(id)

我可以理解它的作用,即它更新/添加列表中的键值对。我无法理解的是,该方法包含两个def update(id:Int,name:String) = list = list + (id -> name)符号,一个在方法定义之后,另一个在列表之后定义了方法实际执行的内容=

两个list + (id -> name)标志需要什么?彼此如何不同?我知道在=符号之后方法体开始了,但这很令人困惑。

2 个答案:

答案 0 :(得分:4)

您可以将其视为:

def update(id: Int, name: String): Unit = {
  // perform update on 'list'
  list = list + (id -> name)
  // return empty (Unit) value
}

答案 1 :(得分:1)

第一个=是分隔方法签名

的原因
def update(id: Int,name: String)

从其定义

list = list + (id -> name)

定义中的=是赋值操作,其中=右侧的表达式被计算并分配给左侧的对象。

相关问题