Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you declare abstract object values and methods in scala?

Tags:

scala

I want to specify an animals color once, and it is the same for all animals of the same species.

So I'd like to do:

abstract object Animal {val color: String}

And then specify individual animals colors with

object Dog extends Animal {val color = "green"}

This needs to be in the object, as I already have a convention which cannot be changed of only making animals with the factory method also declared in the Animal object, and the factory methods needs access to the color. e.g.

abstract object Animal {
   val color: String
   def makeAnimal(args): Animal = ...
}

How do I actually do this in scala, given that "only classes can have declared but undefined members"?

I can think of a hacky way to do this using traits, but I'm hoping there is something better.

[EDIT] So it turns out I can't use traits to hold the values/methods for complicated reasons. The current solution involves staticly registering the child object with the parent object using a trait, and that allows me to access the non-trait values and methods which must be defined in an object. I'm still hoping for a better solution.

like image 518
wn- Avatar asked Jul 29 '11 20:07

wn-


People also ask

How does Scala define abstract method?

In Scala, an abstract class is constructed using the abstract keyword. It contains both abstract and non-abstract methods and cannot support multiple inheritances. A class can extend only one abstract class. The abstract methods of abstract class are those methods which do not contain any implementation.

How do I declare an object in Scala?

In Scala, an object of a class is created using the new keyword. The syntax of creating object in Scala is: Syntax: var obj = new Dog();

How do you implement abstract members in Scala?

To implement Scala abstract class, we use the keyword 'abstract' against its declaration. It is also mandatory for a child to implement all abstract methods of the parent class. We can also use traits to implement abstraction; we will see that later.

Can abstract class have constructor in Scala?

Scala traits don't allow constructor parameters However, be aware that a class can extend only one abstract class.


1 Answers

You can't extend objects, by definition. So yes, you need a trait, but I don't see anything hacky about this:

trait AnimalCompanion {
  val color: String
  def makeAnimal(args): Animal // if you have same args everywhere
}

object Dog extends AnimalCompanion {
  val color = ...
  def makeAnimal(args) = ...
}

or even better

trait AnimalCompanion[A <: Animal] {
  val color: String
  def makeAnimal(args): A
}

class Dog extends Animal

object Dog extends AnimalCompanion[Dog] {
  val color = ...
  def makeAnimal(args): Dog = ...
}
like image 60
Alexey Romanov Avatar answered Oct 31 '22 21:10

Alexey Romanov