I'm currently discovering scala and I was wondering if I could use traits with a factory.
I tried this :
abstract class Foo { ... } object Foo { def apply() = new Bar private class Bar extends Foo { ... } } Foo() with MyTrait // Not working
I guess it's because with
must be preceded by new
.
So is there any way to do this ?
Thank you
FactoryBot's traits are an outstanding way to DRY up your tests and factories by naming groups of attributes, callbacks, and associations in one concise area. Imagine defining factories but without the attributes backed by a specific object.
Rspec has great feature and that is trait. In rspec we create factory for each class which provides the simplest set of attributes necessary to create an instance of that class. Many times we need some attributes which we do not want to add in original factory and at the same time we do not want to repeat it.
Transient attributes are essentially variables local to the factory that do not persist into the created object.
No it is too late, the instance is already created when the apply() method returns.
What you can do is using the traits inside the factory method. The code below is from a rather big code example I am writing:
object Avatar {
// Avatar factory method
def apply(name: String, race: RaceType.Value, character: CharacterType.Value
): Avatar = {
race match {
case RaceType.Dwarf => {
character match {
case CharacterType.Thief => new Avatar(name) with Dwarf with Thief
case CharacterType.Warrior => new Avatar(name) with Dwarf with Warrior
case CharacterType.Wizard => new Avatar(name) with Dwarf with Wizard
}
}
case RaceType.Elf => {
character match {
case CharacterType.Thief => new Avatar(name) with Elf with Thief
case CharacterType.Warrior => new Avatar(name) with Elf with Warrior
case CharacterType.Wizard => new Avatar(name) with Elf with Wizard
}
}
}
}
}
class Avatar(val name: String) extends Character {
...
}
In this code the type (profession and race) of your Avatar is decided in the factory based on the RaceType and CharacterType enumerations. What you have is one factory for all sorts of different types or type combinations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With