Scala immutable objects and traits with val fields

后端 未结 5 1390
难免孤独
难免孤独 2021-02-08 03:04

I would like to construct my domain model using immutable objects only. But I also want to use traits with val fields and move some functionality to traits. Please look at the f

5条回答
  •  没有蜡笔的小新
    2021-02-08 03:33

    This should do what you are looking for:

    trait Request[T <: Request[T]] extends Cloneable {
      this: T =>
      private var rets = 0
      def retries = rets
      def incRetries:T = {
        val x = super.clone().asInstanceOf[T]
        x.rets = rets + 1
        x
      }
    }
    

    Then you can use it like

    case class Download(packageName:String) extends Request[Download]
    val d = Download("Test")
    println(d.retries) //Prints 0
    val d2 = d.incRetries
    println(d2.retries) //Prints 1
    println(d.retries) //Still prints 0   
    

提交回复
热议问题