Reputation: 1418
I'm studying Scala and I'm trying to translate the code of some design pattern from Java to Scala, but I lose some detail.
For example, now I write a simple State but I receive three occurrences of the same error in compile time:
This is the code
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");
}
}
The error occurences are:
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
reading the doc, it likes an uncorrect use of traits, but I'm not using the traits!
The StateA and StateB are the implementing class of class Statelike, what is abstract. No more, no less.
Where's my code error? A too much "Java-style" inheritance? Waht can be a solution?
Thanks in advance
Upvotes: 0
Views: 360
Reputation: 38045
Compiler is puzzled what you are trying to do here:
myState(new StateA)
Well... I'm puzzled too. myState
is a method without parameters.
def myState : Statelike = state
So you could rewrite your code like this:
val ms: Statelike = myState
ms(new StateA)
Since ms
is not a method the last line (ms(new StateA)
) is the shorten version of ms.apply(new StateA)
. But there is no method apply
in class Statelike
.
Maybe you want to call myState.writeName(new StateA)
instead of myState.(new StateA)
, but there is not enough parameters for method writeName
.
Setter
As @AlexIv mentioned: If you are trying to call setter, you should note that it's name is myState_=
, not myState
.
myState_=(new StateA)
With syntax sugar:
myState = new StateA
Upvotes: 4