Scala - Invoking a class by string (with class name) - scala

I have those classes like this:
object Class1 extends parent {
def execute() {
print("Class1")
}
}
object Class2 extends parent {
def execute {
print("Class2")
}
}
Then I have a Runner like this:
object Runner extends runParent {
def manageRun(className: String) = {
def ClassInstance = className match {
case Some("Class1") => Some(Class1)
case Some("Class2") => Some(Class2)
}
ClassInstance.execute()
}
}
There is any way to change this managerRun code and when I create a Class3 I don't need to add a new case in the match?
Thanks!

Related

Define method that could be accessed only from descendants within the same package

I'd like to specify somehow that a method could be accessed only from descendants that are defined in the same package. That is like protected but more restricted.
object Some {
class Base {
modifier[magic] def test() {
println("ok")
}
}
class Ok extends Base {
test()
}
class ShouldFail {
def fail(b : Base) {
b.test()
}
}
}
object Another {
class ShouldFail extends Some.Base {
test()
}
}
That is what I'd like to get
I've got a solution, too verbose and with some overhead for accessing protected methods.
object Some {
private[Some] class Access[T] private[Some] (aFun : () => T) {
private[Some] def apply() : T = aFun()
}
private[Some] object Access {
private[Some] def apply[T](aFun : () => T) : Access[T] = new Access(aFun)
}
class Base {
private[this] def test() {
println("ok")
}
protected val accessTest = Access( () => test() )
}
class Ok extends Base {
accessTest()
}
class ShouldFail {
def fail(b : Base) {
b.accessTest()
}
}
}
object Another {
class ShouldFail extends Some.Base {
accessTest()
}
}
The idea is to wrap method inside an object and chain permission restrictions between access modifiers for accessing object and accessing value inside object. That introduces overhead, though.

How to share functionality between subclasses

I would like subclasses to inject functionality within the base class' apply method:
Base class:
case class BaseClass(data: Json)
object BaseClass {
def apply(data: String) : JsonClass = {
try {
_ //subclass functionality should go here
} catch {
case e: Exception => ErrorJsonClass(data)
}
}
}
object SubClass extends BaseClass {
def apply(data: String) : Json = {
deserialize(data) // this should be called within the base class' apply
}
}
Is there a way to do this without declaring separate methods within the base class?
Ie. Im trying to avoid the following:
object BaseClass {
def apply(data: String) : JsonClass = {
try {
convert(data)
} catch {
case e: Exception => ErrorJsonClass(data)
}
}
def convert(data: String): JsonClass = _
}
object SubClass extends BaseClass {
def convert(data: String) : Json = {
deserialize(data)
}
}

Is there a way in scala using functionality from super class in mixed in trait

I have the following classes/traits setup:
class RestService extends EntityReader[UserEntity]
with EntityReaderExtension {
def serveSomething() = {...}
}
trait EntityReader[EntityType <: StoredEntity] extends RestHelper {
protected def read(id:UUID): Option[EntityType] = {
// Read by id
}
}
trait EntityReaderExtension {
def serveExtensionMethod(id:UUID) = {
// val entity = read(id) match {...}
// copy values to other entity and serve
}
}
Is there a way i can use the method from trait EntityReader in trait EntityReaderExtension without extending?
I think what you want is an explicitly typed self reference.
trait EntityReaderExtension { self: EntityReader[_] =>
def serveExtensionMethod(id:UUID) = {
val entity = self.read(id) match {...}
}
}

How to extend an object in Scala with an abstract class with constructor?

How to extend an object in Scala with an abstract class that has a constructor, and apply method of the object returns the object as subtype of the abstract?
for example :
abstract class AbstractResource(amount:Int) {
val amount:Int
def getAmount = amount
}
case object Wood extends AbstractResource{
def apply(amount: Int) = {
// something that returns the subtype
}
}
I think a good solution is:
abstract class AbstractResource {
val amount: Int = 0
def getAmount = amount
}
case object Wood extends AbstractResource {
def apply(quantity: Int) = {
new AbstractResource {
override val amount = quantity
}
}
}
But my problem is I can't edit AbstractResource
I have no idea why should Wood extend AbstractResource, but this works:
class AbstractResource(val amount:Int) {
def getAmount = amount
}
case object Wood extends AbstractResource(0) {
def apply(amount: Int) = {
new AbstractResource(amount)
}
}

How to determine if `this` is an instance of a class or an object?

Suppose I have two descendants of an abstract class:
object Child1 extends MyAbstrClass {
...
}
class Child2 extends MyAbstrClass {
}
Now I'd like to determine (preferably in the constructor of MyAbstrClass) if the instance being created is an object or something created by new:
abstract class MyAbstrClass {
{
if (/* is this an object? */) {
// do something
} else {
// no, a class instance, do something else
}
}
}
Is anything like that possible in Scala? My idea is to collect all objects that descend from a class into a collection, but only object, not instances created by new.
Something like:
package objonly
/** There's nothing like a downvote to make you not want to help out on SO. */
abstract class AbsFoo {
println(s"I'm a ${getClass}")
if (isObj) {
println("Object")
} else {
println("Mere Instance")
}
def isObj: Boolean = isObjReflectively
def isObjDirty = getClass.getName.endsWith("$")
import scala.reflect.runtime.{ currentMirror => cm }
def isObjReflectively = cm.reflect(this).symbol.isModuleClass
}
object Foo1 extends AbsFoo
class Foo2 extends AbsFoo
object Test extends App {
val foob = new Foo2
val fooz = new AbsFoo { }
val f = Foo1
}
Here's a rather cheesy idea:
trait X {
println("A singleton? " + getClass.getName.endsWith("$"))
}
object Y extends X
Y // objects are lazily initialised! this enforces it
class Z extends X
new Z