Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Generic array with default parameter value in constructor

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:

  1. Why capacity parameter is not available for other parameters in constructor definition?
  2. Why ClassTag ev is 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.

like image 593
JohnGray Avatar asked Aug 02 '26 10:08

JohnGray


1 Answers

You can only use values from previous argument lists for default values in constructors and methods, not from the same one:

class ImmutableStack[E <: Any](capacity: Int = 10)(elems: Array[E] = new Array[E](capacity))(implicit ev: ClassTag[E])

To work around inability to use implicit class tag, the best I can offer is

class ImmutableStack[E <: Any : ClassTag](capacity: Int = 10)(elems: Array[E] = null) {
  val realElems = if (elems != null) elems else new Array[E](capacity)
}
like image 127
Alexey Romanov Avatar answered Aug 04 '26 11:08

Alexey Romanov