1

I ran into an interesting scenario in Scala. It seems then I have a base trait that defines other traits, the implementation cannot find the base trait not matter what.

I created this base trait simple for convenience that I don't need to redefined these traits on every implementation. Do anyone know why this doesn't work?

object Base { trait Create trait Delete } trait BaseTrait { trait Create extends Base.Create trait Delete extends Base.Delete } object Implementation extends BaseTrait object Something { class SomeClass extends Implementation.Create //The trait is not defined. } 

Update:
The question has been cleared up a bit so that its more precise. The solution as @BrianHsu pointed out is that trait cannot be inherited.

5
  • 5
    I can't reproduce this issue in a REPL session. Are you sure this is the actual code? Commented Nov 16, 2015 at 11:36
  • I copy pasted the code and did not get any errors. I am using scala 2.11.6 I have put the entire source in a single scala file. The problem should be something not captured in the example. Commented Nov 16, 2015 at 11:39
  • Hi @GabrielePetronella, example is updated above Commented Nov 17, 2015 at 6:27
  • In the future instead of "doesn't work" please be specific, give us the same information that scalac was kind enough to give you (even if you don't comprehend it). Commented Nov 17, 2015 at 8:02
  • @nafg fair enough. my bad. Commented Nov 17, 2015 at 8:17

1 Answer 1

2

This block of code is fine:

object Base { trait Event trait Command } 

The following block will run into to trouble:

trait BaseTrait { trait Event extends Event trait Command extends Command } 

But Scala compiler says it very clearly.

test.scala:7: error: illegal cyclic reference involving trait Event trait Event extends Event ^ test.scala:8: error: illegal cyclic reference involving trait Command trait Command extends Command 

Of course you cannot do this, just like you could not do the following in Java:

class HelloWorld extends HelloWorld 

You have to specify that what you extend is actually Base.Event / Base.Command, so it will only work if you write it as:

trait BaseTrait { trait Event extends Base.Event trait Command extends Base.Command } 

Another problem in your code it the last Something object, it does not make sense at all:

object Something { Implementation.Event Implementation.Commannd } 

So compiler give you a clear error message:

test.scala:14: error: value Event is not a member of object Implementation Implementation.Event ^ test.scala:15: error: value Commannd is not a member of object Implementation Implementation.Commannd 

It's quite obvious, an trait in Scala is much like interface in Java, you should not use it as it is a field.

Sign up to request clarification or add additional context in comments.

1 Comment

Got it. So traits being what they are, can't be inherited by the Implementation object.