Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't Scala traits allow constructor parameters?

Tags:

scala

I'm new to Scala, coming from Java, and I was just reading about traits. One thing that gets mentioned often is that traits don't (can't? won't?) have constructor parameters. I was curious to know if there was a reason for this.

Coming from a long ago maths/computer-science background I was was wondering if this was an inevitable consequence because of some language design decision, or if it was a conscious decision to avoid some inheritance/mix-in problem or another?

Was hoping someone might know because it feels like there might be something interesting behind the fact.

like image 776
moncheery Avatar asked Apr 01 '15 13:04

moncheery


2 Answers

The other answers describe the language; I suspect your question may really be "why is it designed in this way".

I believe it arises out of the awkwardnesses and verboseness that would arise when extending multiple traits, especially with overrides and with types, and various mix-in strategies.

The Cake Pattern often results in various traits providing missing bits to each other in a way that is totally invisible - by design - in the mixing class. And mixing can be bi-directional, using self-types. So the construction of a class from traits can be a very messy business for the compiler. Scala often trades simplicity of compiler design and implementation for simplicity of language use and code reduction, and this is certainly a good example.

So while there may be simple, hierarchical cases where having a constructor might be useful and sufficient, it would almost certainly have to be redundant of other mechanisms for more difficult, non-hierarchical scenarios.

like image 191
Ed Staub Avatar answered Oct 27 '22 00:10

Ed Staub


Scala 3 will allow trait parameters. Here's a sample from the docs

trait Greeting(val name: String) {
  def msg = s"How are you, $name"
}

class C extends Greeting("Bob") {
  println(msg)
}
like image 36
joel Avatar answered Oct 27 '22 00:10

joel