Case class copy() method abstraction

前端 未结 5 845
孤独总比滥情好
孤独总比滥情好 2021-01-02 02:08

I would like to know if it is possible to abstract the copy method of case classes. Basically I have something like sealed trait Op and then something like

5条回答
  •  [愿得一人]
    2021-01-02 02:30

    Upvoted Ben's answer. But what if you wanted to something like this:

    sealed trait Op 
    case class Push(value: Int, context:String) extends Op
    case class Pop(context:String) extends Op
    
    val stackOps = List(Push(3, "foo"), Pop("foo"))
    
    def copyToContext(newContext:String, ops:List[Op]): List[Op] = {
        // ... ?
    }
    
    val changedOps = copyToContext("bar", stackOps)
    
    // would return: List(Push(3, "bar"), Pop("bar"))
    

提交回复
热议问题