I'm very beginner Scala programmer who's coming from Java. I'm trying to build an understanding of Scala's traits, as a superior alternative to Java's interfaces. In this case, I want to create a trait which, when implemented, will require an object to have attributes, and one or more of those attributes will themselves be objects with required traits. The following code demonstrates what I want, but it doesn't currently work.
trait Person{ def name: String def age: Int def address extends Address } trait Address{ def streetName: String def streetNumber: Int def city: String } object aPerson extends Person { override val name = "John" override age = 25 override address = object { //this doesn't work def streetName = "Main St." def streetNumber = 120 def city = "Sometown" } } So I want the Person trait to require the object to have an Address attribute, which itself has some required attributes. The compiler doesn't like the above code defining the address in aPerson.
What's the right way to do this?
Bonus question: Let's say the Address trait is only used here. Is there a way to define the Address trait anonymously inside the Person trait so it won't clutter the file?