[英]type does not take parameters Scala
I have case class State and want to extend Variable class from it; 我有案例类State,并且想要从中扩展Variable类; but in Variable class only need value in constructor.
但是在Variable类中,只需要在构造函数中使用值即可。 Where can I put
run
function? 我可以在哪里放置
run
功能?
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)
}
UPDATE I've changed to something like this: 更新我已经变成了这样的东西:
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))
}
But I've gotten error: 但是我得到了错误:
type mismatch; 类型不匹配; found : com.libs.State[A,A] required: com.libs.Variable[A] Variable.scala /scala/src/com/libs line 4 Scala Problem
找到:com.libs.State [A,A]必需:com.libs.Variable [A] Variable.scala / scala / src / com / libs第4行Scala问题
The problem is that you cannot define a Variable
using map
, since map
defines a State
which is only a super-type of Variable
. 问题是您不能使用
map
定义Variable
,因为map
定义了一个State
,它只是Variable
的超类型。 How can your program know how to set the additional information of your subclass, using only map
? 您的程序如何仅使用
map
知道如何设置子类的其他信息?
However, if you define type Variable[+A] = State[A, A]
, so that it is not a subclass but an alias for the same class, you will have some variance errors, since State
is invariant in its type parameter S
, so Variable
must be too. 但是,如果您定义
type Variable[+A] = State[A, A]
,因此它不是子类而是同一类的别名,则由于State
在其类型参数S
是不变的,因此会出现一些方差错误。 ,因此Variable
必须如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.