I have a few questions about scala generics and default parameter values.
Suppose, I have the following class definition (where Stack[E] is a trait)
class ImmutableStack[E](capacity: Int = 10, elems: Array[E] = new Array[E](capacity))(implicit ev: ClassTag[E]) extends Stack[E]
When I try to compile that code it gives two errors:
scala: cannot find class tag for element type E
class ImmutableStack[E <: Any](capacity: Int = 10, elems: Array[E] = new Array[E](capacity))(implicit ev: ClassTag[E]) extends SedgewickStack[E] {
^
And:
scala: not found: value capacity
class ImmutableStack[E <: Any](capacity: Int = 10, elems: Array[E] = new Array[E](capacity))(implicit ev: ClassTag[E]) extends SedgewickStack[E] {
^
Could someone explain me:
- Why capacity parameter is not available for other parameters in constructor definition?
- Why ClassTag
evis not available for default parameter value i.e.new Array[E](capacity)?
When I remove default value for elem parameter - everything works fine.
Thanks in advance for any answer.
capacityis actually in scope inside the constructor declaration. For that matter, I don't know wether any language allows cross-referencing constructor or function parameters; you can only access them in the body.capacityis not a problem. You just should move it to additional parameters group. This works finedef test(a: Int)(b: Int = a) = a + b; test(1)(). But you can't access parameter from next group (ev).class Test(a: Int)(b: Int = a) { val c = a + b }; new Test(1)().cworks fine. In other case you could use a factory method.