Case class constructor argument type depending on the previous argument value

前端 未结 1 1206
伪装坚强ぢ
伪装坚强ぢ 2021-01-04 06:20

I am trying to do the following

trait Stateful {
  type State
}

case class SystemState(system: Stateful, state: system.State) // does not compile

1条回答
  •  再見小時候
    2021-01-04 06:34

    The multiple parameter list approach for dependent types unfortunately is not supported for constructors, so no, you will have to introduce a type parameter.

    You could hide that fact if it becomes bothering, though

    trait Stateful {
      type State
    }
    
    object SystemState {
      def apply(system: Stateful)(state: system.State): SystemState = 
        new Impl[system.State](system, state)
    
      private case class Impl[S](val system: Stateful { type State = S }, 
                                 val state: S)
        extends SystemState {
        override def productPrefix = "SystemState"
      }
    }
    trait SystemState {
      val system: Stateful
      val state: system.State
    }
    
    case object Test extends Stateful { type State = Int }
    val x = SystemState(Test)(1234)
    

    0 讨论(0)
提交回复
热议问题