【问题标题】:Case class constructor argument type depending on the previous argument value案例类构造函数参数类型取决于前一个参数值
【发布时间】:2015-05-16 14:28:53
【问题描述】:

我正在尝试执行以下操作

trait Stateful {
  type State
}

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

state的类型取决于system的(值)。但是,不支持:

非法依赖方法类型:参数出现在同一节或更早的另一个参数的类型中

使用函数参数,我可以将参数拆分为两个参数列表,这对于案例类构造函数是不可能的:

def f(system: Stateful)(state: system.State): Unit = {} // compiles

我能做的最好的就是:

case class SystemState[S](system: Stateful { type State = S }, state: S) // compiles

但我认为没有类型参数应该是可能的,因为在 dotty 中,我认为类型参数被取消了类型成员的糖分。

那么我的问题是,这可以不用类型参数来表达吗?

在更一般的情况下,我正在探索类型参数在多大程度上可以被类型成员替换,什么时候这样做是个好主意。

【问题讨论】:

    标签: scala case-class dependent-type dotty


    【解决方案1】:

    不幸的是,依赖类型的多参数列表方法是not supported for constructors,所以不,你必须引入一个类型参数。

    不过,如果它变得烦人,你可以隐藏这个事实

    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)
    

    【讨论】:

      猜你喜欢
      • 2011-06-04
      • 1970-01-01
      • 2021-10-11
      • 2017-09-14
      • 2019-06-10
      • 2017-03-25
      • 2011-11-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多