类扩展了集合的Case类

时间:2017-03-06 14:52:41

标签: scala inheritance case-class

我是否可以创建一个仅用于Collecetion的案例类(读取HashSet)和一个扩展此案例类以存储有用信息的类?

我的意思是这样的:

case class User(id: String)

class UserInfo(id: String) extends User(id) {

  var time = 0
  var sum = 0

}

我只想使用UserInfo在HashSet中存储有关User的信息,但是使用case类实现以及已经为集合实现的所有有用方法(aka equalshashCode

关注Yuval Itzchakov评论:

abstract class User(val id: String) {

  private var time = 0L
  private var sum = 0L

  def addTime(_time: Long) = time += _time
  def addSum(_sum : Long) = sum  += _sum 

  def getTime() = time 
  def getSum() = sum  

}

case class UserInfo(override val id : String) extends User(id)

private vars因为我想保证我只能添加信息(吸气者也一样)

1 个答案:

答案 0 :(得分:2)

可变性是一个坏主意,应该几乎总是避免。在保持不变性的同时做一切你需要的方法是使用伴侣对象:

case class User(id: String, time: Long)

object User {
   def addTime(user: User, time: Long): User = user.copy(time = user.time + time)
}

val users = Set(User("John", 5), User("Mary", 10))
val sumTime = users.foldLeft(0L)((sum, user) => sum + user.time)
val usersWithTimeAdded = users.map(User.addTime(_, 2))