0

I created a Trait to combine all common ViewHolder properties in one place.

trait MyHolder extends RecyclerView.ViewHolder {
  def view: View = this.itemView
}

Then I wanted to use this trait in my classes like so:

case class MyItemHolder(override val view: View, items: Array[String]) extends MyHolder

Unfortunately it gives me an error.

Not enough arguments for constructor ViewHolder: (x$1: android.view.View)android.support.v7.widget.RecyclerView.ViewHolder.
[error] Unspecified value parameter x$1.
[error]   case class MyItemHolder(override val view: View, items: Array[String]) extends MyHolder

I can get it to compile with this class definition but it seems redundant.

case class MyItemHolder(override val view: View, items: Array[String]) extends RecyclerView.ViewHolder(view) with MyHolder 

How can I get rid of RecyclerView.ViewHolder(view)?

user3350744
  • 449
  • 1
  • 5
  • 12

1 Answers1

0

You cannot drop the constructor of RecyclerView.ViewHolder because you have to tell Scala how to call the super constructor. In general you don't need to override the constructor parameter, but you can use any arbitrary value:

class BaseClass(val x: Int)
class SubClass1 extends BaseClass(3)
// or
class SubClass2(val y: Int) extends BaseClass(y)
// or
class SubClass3(override val x: Int) extends BaseClass(x)

As already mentioned here SubClass2 and SubClass3 are equivalent.

One of the characteristics of a trait is, that it has no constructor (for keeping single inheritance). Additionaly a trait that extends a class means that this trait can only be used in that class or a subclass of this:

class BaseClass
class OtherClass
trait T extends OtherClass
class OtherSubClass extends OtherClass

class SubClass1 extends BaseClass with T // error: illegal inheritance;
class SubClass2 extends T // okay*
class SubClass3 extends OtherSubClass with T // okay

*SubClass2 only works because the primary constructor of OtherClass is empty. Otherwise you have to call the constructor explicitly as in the first code snippet.

Putting that together, there is no way of calling the constructor implicitly.

Jojo
  • 357
  • 2
  • 10