简体   繁体   中英

Accompanying object for trait in Scala

I try to write general apply method to serve as a factory method for child classes. What I came up with is following:

trait A 

object A {
    def apply[T <: A](someParam: String): T {
        new T()
    }
}

class B private extends A 
class C private extends A

So one can create new B or C instance:

def main(args: Array[String]): Unit = {
    A[B]("test")
}

Is it acceptable that trait has an accompanying object?Is there a better way to implement this?

You could:

  trait A

  object A {
    def apply[T <: A ](someParam: String) (implicit ev: ClassTag[T]): T ={
      ev.runtimeClass.newInstance().asInstanceOf[T]
    }
  }

But its not very useful with varying constructor's for each sub class

  sealed trait A

  object A {
    def apply[T <: A](someParam: String)(implicit ev: T): T = {
      ev
    }
  }

  class B(n: Int) extends A    
  class C(n: String) extends A

  object B {
    implicit def defaultCons: B = new B(1)
  }

  object C {
    implicit def defaultCons: C = new C("hi")
  }

Or you could also go via combination of ClassTag approach with pattern match based on the class instead of using reflection for instantiation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM