A common attribute that takes a class and its associated object as a type parameter

So, I want the common attribute to take a class with a companion object that inherits from a specific base class and refers to both the companion object and the class itself as a type parameter. In this way,

abstract class BaseModel[T] {
  def all: Seq[T]
}

case class Customer(email: String, password: String)

object Customer extends BaseModel[Customer]

// This trait is my issue
trait BaseCrud[T] { 
  def table[T](f: T => String): String = {
    T.all.map(f _).mkString("")
  }
}

object Controller with BaseCrud {
  def foo = table(_.email)
}

I had some solutions for this trait that were closer, but I redid it so you can see what I'm trying to do.

thank

UPDATE

So, I went with a solution from Frank below, but I managed to solve my original riddle. Although, in this case, the solution was a little ugly, I will include it here for completeness.

abstract class BaseModel[T] {
  def all: Seq[T] = Seq()
}

case class Customer(email: String, password: String)

object Customer extends BaseModel[Customer]

trait BaseCrud[T, U <: BaseModel[T]] { 
  def table(f: T => String)(implicit obj: U): String = {
    obj.all.map(f(_)).mkString("")
  }
}

object Controller extends BaseCrud[Customer, Customer.type] {
  implicit val model = Customer
  def foo = table(_.email)
}

, , BaseCrud, BaseCrud.table Controller.model. . , Customer.type .

+5
2

.. :

  • def table[T](... , T . , , def table(...
  • object Controller with BaseCrud { :
    • extends with. , /.
    • BaseCrud , , - BaseCrud[Customer]
  • , , : T . , T.something. - - , , .

, , , :

abstract class BaseModel[T] {
  def all: Seq[T]
}

case class Customer(email: String, password: String)

object Customer extends BaseModel[Customer] {
  def all = List[Customer]() // have to define this
}

trait BaseCrud[T] {
  val companion : BaseModel[T]
  def table(f: T => String): String = {
    companion.all.map(f).mkString("")
  }
}

object Controller extends BaseCrud[Customer] {
  val companion = Customer
  def foo = table(_.email)
}
+6

, scala self BaseCrud, , . . .

trait BaseCrud[T] {
  self: BaseModel[T] =>
  def table(f: T => String): String =
    all.map(f).mkString("")
}

object Controller extends BaseModel[Customer] with BaseCrud[Customer]{
  def foo = table(_.email)
}
+1

All Articles