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:
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.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With