2

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?

2 Answers 2

2

I think this is what you're trying to do.

trait Person{ val name: String val age: Int val address: Address } trait Address{ val streetName: String val streetNumber: Int val city: String } object aPerson extends Person { val name = "John" val age = 25 val address: Address = new Address { //this now works val streetName = "Main St." val streetNumber = 120 val city = "Sometown" } } 

The Address trait can be made anonymous, but then traits like Person can't reference it because it has no named type.

trait Person{ val name: String val age: Int //val address: ?type? } object aPerson extends Person { val name = "John" val age = 25 val address = new { //this also works val streetName = "Main St." val streetNumber = 120 val city = "Sometown" } } aPerson.address.city //res0: String = Sometown 
Sign up to request clarification or add additional context in comments.

1 Comment

The second suggestion regarding making it anonymous doesn't work, because without a named type, other code can't do type-checking, which totally makes sense. So I guess I just won't declare it anonymously. But the first piece of code works perfectly!
1

You can override a def with an object.

trait Person { def name: String def age: Int def address: Address } object aPerson extends Person { val name = "John" val age = 25 object address extends Address { val streetName = "Main St." val streetNumber = 120 val city = "Sometown" } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.