5

Case class can extend trait and implement it using its fields.

trait IWork { def itWorks: String } case class Example(itWorks: String) extends IWork 

It compiles and works fine. Could you please explain, why it can't be compiled?

trait IsAfter { def after(test: Date): Boolean } case class Example2(after: Date => Boolean) extends IsAfter 

1 Answer 1

7

You can implement an abstract def using a val and that's what you're doing in the first example.

However, you're working under the assumption that methods and functions are the same thing. Unfortunately this is not the case, despite the best efforts by the scala compiler to hide this fact.

Here's a thorough explanation of the differences.

For this reason you cannot implement an abstract method using a function, but you have to do something like

class Example2(a: Date => Boolean) extends IsAfter { def after(test: Date) = a(test) } 
Sign up to request clarification or add additional context in comments.

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.