加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 获取更新的不可变对象的更短方法?

发布时间:2020-12-16 09:05:58 所属栏目:安全 来源:网络整理
导读:我有一个带有几个参数的类,例如类Building(val a:Int,val b:Int,val c:Int).这个代码我必须更新它是这样的: def updatedA(a: Int): Building = new Building(a,this.b,this.c)def updatedB(b: Int): Building = new Building(this.a,b,this.c) 是否有更
我有一个带有几个参数的类,例如类Building(val a:Int,val b:Int,val c:Int).这个代码我必须更新它是这样的:

def updatedA(a: Int): Building = new Building(a,this.b,this.c)
def updatedB(b: Int): Building = new Building(this.a,b,this.c)

是否有更短的方法来获取如下更新的对象?

def updatedA(newA: Int): Building = new { val a = newA } extends this // doesn't compile/ type is AnyRef instead of Building

解决方法

你看过copyWith() construction mechanism吗?

The copyWith method takes advantage of Scala 2.8’s default arguments.
For each field in the class,it has a parameter which defaults to the
current value. Whichever arguments aren’t specified will take on their
original values. We can call the method using named arguments (also in
Scala 2.8).

val newJoe = joe.copyWith(phone = “555-1234”)

或者查看copy mechanism的案例类别.

/* The real power is the copy constructor that is automatically
generated in the case class. I can make a copy with any or all
attributes modifed by using the copy constructor and declaring which
field to modify */

scala> parent.copy(right = Some(node))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读