Reputation: 7901
I have an abstract superclass with a variety of stateless implementations. It seems like the thing to do is make the abstract superclass a class
, and make each implementation an object
because I only ever need one of each.
This is a toy example, but it shows the compile error I’m getting:
// Tramsformer.scala
class Transformer {
def transform(value : String) : String
}
object Transformer {
getTransformer(String : name) : Transformer = {
name match {
case "upper" => UpperTransformer
// I'm getting "Cannot Resolve Symbol" on UpperTransformer,
// even though they're in the same package.
case _ => throw new IllegalArgumentException("...")
}
}
}
// ---
// UpperTransformer.scala is in the same package
object UpperTransformer extends Transformer {
override def transform(vlaue : String) = foo.toUpperCase()
}
I’m really shooting for some sort of dynamic dispatch on (dataProvider, desiredAction) here.
Then some class can call Transformer.getTransformer("upper").transform("stack-overflow")
without making any unnecessary objects.
Any idea what I should be doing differently? Should I stop worrying about premature optimization and learn to love the instance?
Upvotes: 0
Views: 224
Reputation: 370435
The problem isn't visibility, it's that you simply do not define an object named UpperTransformer
anywhere - only a class. If you replace class UpperTransformer
with object UpperTransformer
, your code should work fine.
Upvotes: 2