我有一个班级的人
class Person(val name: String, val height : Int, val weight: Int)
Run Code Online (Sandbox Code Playgroud)
我想copy()为我的类编写方法,它可以像复制方法一样使用case类(复制和更新对象的属性)
我知道copy()自带的是案例类,但我没有使用它们,所以我想为我的班级做同样的事情
请指导我怎么做?
mat*_*its 12
只需创建一个复制方法,其中包含类定义中的所有字段作为参数,但使用现有值作为默认参数,然后使用所有参数创建新实例:
class Person(val name: String, val height : Int, val weight: Int) {
def copy(newName: String = name, newHeight: Int = height, newWeight: Int = weight): Person =
new Person(newName, newHeight, newWeight)
override def toString = s"Name: $name Height: $height Weight: $weight"
}
val person = new Person("bob", 183, 85)
val heavy_person = person.copy(newWeight = 120)
val different_person = person.copy(newName = "frank")
List(person, heavy_person, different_person) foreach {
println(_)
}
Run Code Online (Sandbox Code Playgroud)