我正在研究 Scala,我正在尝试将一些设计模式的代码从 Java 转换为 Scala,但我丢失了一些细节。
例如,现在我编写了一个简单的State,但在编译时我收到了三个相同的错误:
这是代码
abstract class Statelike {
def writeName(STATE_CONTEXT : StateContext , NAME : String): Unit
}
class StateA extends Statelike {
override def writeName( STATE_CONTEXT : StateContext , NAME : String) : Unit = {
println(NAME.toLowerCase());
STATE_CONTEXT.myState(new StateB) **//same error**
}
}//end StateA
class StateB extends Statelike {
var count = 0;
override def writeName( state_contest: StateContext , name: String) : Unit = {
println(name.toUpperCase());
count+1;
var conto2 = count;
if (conto2 > 1) {
state_contest.myState(new StateA) **//same error**
}
}
}//StateB
class StateContext {
var state : Statelike = null
def StateContext() {
myState(new StateA) **//same error**
}
def myState_=(s1 : Statelike ) = {state = s1}
def myState : Statelike = state
def writeName ( NAME : String): Unit = {
myState.writeName(this, NAME);
}
}//end StateContext
object TestClientState {
def main( args : Array[String]) {
var SC = new StateContext();
SC.writeName("Monday");
SC.writeName("Tuesday");
SC.writeName("Wednesday");
SC.writeName("Thursday");
SC.writeName("Friday");
SC.writeName("Saturday");
SC.writeName("Sunday");
}
}
发生的错误是:
State.scala:12: error: Statelike does not take parameters
STATE_CONTEXT.myState(new StateB)
^
State.scala:26: error: Statelike does not take parameters
state_contest.myState(new StateA)
^
State.scala:37: error: Statelike does not take parameters
myState(new StateA)
^
three errors found
阅读文档,它喜欢不正确地使用特征,但我没有使用特征!
StateA和StateB是Statelike类的实现类,是抽象的。不多也不少。
我的代码错误在哪里?过多的“Java 风格”继承?什么可以解决?
提前致谢