How to mix-in a trait to instance?

前端 未结 5 1408
日久生厌
日久生厌 2020-12-04 12:04

Given a trait MyTrait:

trait MyTrait {
  def doSomething = println(\"boo\")
}

it can be mixed into a class with extends<

5条回答
  •  囚心锁ツ
    2020-12-04 12:34

    Why not use Scala's extend my library pattern?

    https://alvinalexander.com/scala/scala-2.10-implicit-class-example

    I'm not sure what the return value is of:

    var o = DBHelper.loadMyEntityFromDB(primaryKey);

    but let us say, it is DBEntity for our example. You can take the class DBEntity and convert it to a class that extends your trait, MyTrait.

    Something like:

    trait MyTrait {
      def doSomething = {
        println("boo")
      }
    }
    
    class MyClass() extends MyTrait
    
    // Have an implicit conversion to MyClass
    implicit def dbEntityToMyClass(in: DBEntity): MyClass = 
    new MyClass()
    

    I believe you could also simplify this by just using an implicit class.

    implicit class ConvertDBEntity(in: DBEntity) extends MyTrait
    

    I particularly dislike the accepted answer here, b/c it overloads the :: operator to mix-in a trait.

    In Scala, the :: operator is used for sequences, i.e.:

    val x = 1 :: 2 :: 3 :: Nil
    

    Using it as a means of inheritance feels, IMHO, a little awkward.

提交回复
热议问题