Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/apache/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
类型不接受Scala参数_Scala_Constructor - Fatal编程技术网

类型不接受Scala参数

类型不接受Scala参数,scala,constructor,Scala,Constructor,我有case类State,希望从中扩展变量类;但在变量类中只需要构造函数中的值。我可以将运行功能放在哪里 case class State[S, +A](run: S => (A, S)) { //.....has `map` function def map[B, X >: State[S, B]](f: A => B): X = State(state => { val (a, s2) = run(state) (f(a), s2)

我有case类State,希望从中扩展变量类;但在变量类中只需要构造函数中的值。我可以将
运行
功能放在哪里

case class State[S, +A](run: S => (A, S)) {
//.....has `map` function
  def map[B, X >: State[S, B]](f: A => B): X =
    State(state => {
      val (a, s2) = run(state)
      (f(a), s2)
    })
}

class Variable[+A](value: A) extends State[A, A] { // ERROR

  def get: Variable[A] =
    map(x => x)
  def set(newValue: A): Variable[A] =
    map(_ => newValue)
}
更新 我改成这样:

class Variable[+A](value: A, run: A => (A, A)) extends State[A, A](run) {
  def get: Variable[A] =
    map(x => x) // ERROR HERE
  def set(newValue: A): State[A, A] =
    map(_ => newValue)
}
object Variable {
  def create[A](value: A): Variable[A] = new Variable[A](value, x => (x, x))
}
但我有一个错误:


类型失配;发现:com.libs.State[A,A]required:com.libs.Variable[A]Variable.scala/scala/src/com/libs第4行scala问题

问题是无法使用
map
定义
变量
,因为
map
定义了
状态
,它只是
变量
的超类型。您的程序如何知道如何仅使用
map
设置子类的附加信息

但是,如果定义
type变量[+A]=State[A,A]
,使其不是子类而是同一类的别名,则会出现一些差异错误,因为
State
在其类型参数
S
中是不变的,因此
Variable
必须也是不变的