如何使用短参数列表调用Scala函数?

时间:2014-09-01 07:20:06

标签: scala copy

假设我有一个带有更新方法的Scala类:

case class User (id: Integer, name: String, surname: String, address: String) {
    def update (name: String, surname: String, address: String): Unit = {
        copy (name, surname, address)
    }        
}

Scala是否可以使用一个或两个参数调用更新函数并将调用委托给复制函数?像这样:

val user: User = User (1, "name", "surname", "address")
user.update(name: "name") // Here it delegate to call copy (name)

或者我是否必须为每种情况复制并粘贴每个更新功能?

1 个答案:

答案 0 :(得分:2)

考虑

case class User (id: Integer, name: String, surname: String, address: String)

其中成员类型遵循成员名称。

然后直接调用copy

val userA = User(1,"a","b","c")
userA: User(1,a,b,c)

val userA2 = a.copy(2)
userA2: User(2,a,b,c)

val userBB = a.copy(name = "bb")
userBB: User(1,bb,b,c)