0

How to create an objectthat extends a trait and uses early definition syntax?

Let's say we have two traits:

trait Trait {
  val value : String
}

trait Simple

Let's say we have also a simple class:

class Class

We can create a new object of type Class and make it extend a Simple trait:

new Class extends Simple

Is it possible to create a new object of type Class that extends the Trait and uses the early definition syntax to set value member? I tried something like:

     new Class  extends { override val value = "42" } with Trait

But this gives a syntax error:

Error:(12, 17) ';' expected but 'extends' found.
new Class extends { val value = "42" } with Trait

3
  • 1
    Can you clarify a bit more what you're trying to do? Why can't you just have this set up like a normal class? I suspect you want a lazy val, but can't find anything on the syntax you're referring to. Commented Aug 6, 2019 at 18:28
  • @Ethan Ooops, I meant early definition syntax. Actually, I have been just learning scala and just wondering, whether one can use that syntax when creating a new object. Commented Aug 6, 2019 at 18:31
  • Why can't you override the value in the body? Commented Aug 6, 2019 at 18:39

1 Answer 1

0
trait T { val value: String }
class C
new C with T { val value = "ok" } 
Sign up to request clarification or add additional context in comments.

2 Comments

Can you add some context around your answer?
@atymic The only "context around" that I would have been able to produce could have been "The right way to do that is ... ". But I was just afraid it would be just a redundant decoration on top of the implicit context determined by the question. I could have stated that using Class and Trait for class and trait names is a bad practice (readability and eventual collision), but it's about teaching. I like reading answers that explain complex things, but I prefer minimalist answers to minimal questions. Thanks though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.