Scala Object Factory based on Type Information

37 views
Skip to first unread message

Joe San

unread,
Jul 25, 2016, 5:24:32 PM7/25/16
to scala-user

I have a trait which is generic and goes like this:

trait MyTrait[T] {
  def doSomething(elems: Seq[T])
}

I then have a object factory whose definition goes like this:

object MyTraitFactory {
  def apply[T](param1: Boolean, param2: Boolean): MyTrait[T] = {
    // based on the type of T, I would like to instantiate sub types
  }
}

I have come concrete implementations that are for example:

class MyStringTrait extends MyTrait[String]

class MyIntTrait extends MyTrait[Int]

I now need that magic bit that would look for the type in my object factory and instantiate the corresponding implementations. Any suggestions?

Clint Gilbert

unread,
Jul 25, 2016, 5:32:22 PM7/25/16
to scala...@googlegroups.com
If you want to make different objects based on some type parameter T,
and you want that checked at compile time, your best bet is a type class:

//your type class
trait Creator[T] {
def create: MyTrait[T]
}

//putting default type class instances in this companion object
//lets you use them without noisy imports
object Creator {
implicit object StringCreator extends Creator[String] {
def create: MyTrait[String] = new MyStringTrait
}

implicit object IntCreator extends Creator[Int] {
def create: MyTrait[Int] = new MyIntTrait
}
}

Then change MyTraitFactory.apply to

def apply[T : Creator](param1: Boolean, param2: Boolean): MyTrait[T] = {
implicitly[Creator[T]].create //or maybe use the params, whatever
}

which is shorthand for

def apply[T](
param1: Boolean,
param2: Boolean)(implicit creator: Creator[T]): MyTrait[T] = {

creator.create //or maybe use the params, whatever
}

TLDR: Google for type classes, that should get you started.

On 07/25/2016 05:24 PM, Joe San wrote:
> I have a trait which is generic and goes like this:
>
> |traitMyTrait[T]{defdoSomething(elems:Seq[T])}|
>
> I then have a object factory whose definition goes like this:
>
> |objectMyTraitFactory{defapply[T](param1:Boolean,param2:Boolean):MyTrait[T]={//
> based on the type of T, I would like to instantiate sub types}}|
>
> I have come concrete implementations that are for example:
>
> |classMyStringTraitextendsMyTrait[String]classMyIntTraitextendsMyTrait[Int]|
>
> I now need that magic bit that would look for the type in my object
> factory and instantiate the corresponding implementations. Any suggestions?
>
> --
> You received this message because you are subscribed to the Google
> Groups "scala-user" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to scala-user+...@googlegroups.com
> <mailto:scala-user+...@googlegroups.com>.
> For more options, visit https://groups.google.com/d/optout.

--



signature.asc
Reply all
Reply to author
Forward
0 new messages