简体   繁体   中英

How can I return a scala “object” as if it's a class instance?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM