Manu Chadha Manu Chadha - 5 days ago 5
Scala Question

unable to return an Array from a class

Trying to understand 'apply' method. I want to create a class which returns either a List, Array or a Set depending on the argument passed. The code works for List and Set but not for Array. I am not able to understand the issue

class CollectionFactory [A](s:String){}
object CollectionFactory {
def apply[A](s: String): Traversable[A] = {
s match {
case "list" => {
List[A]()
}
//this doesnt work. It seems using [A] is incorrect. How do I specify the type?
/*
case "array" => {
new Array[A](1)
}
*/
case _ => {
Set[A]() }
}
}
}

val c = CollectionFactory[Int]("list")
c: Traversable[Int] = List()

CollectionFactory[String]("list")
res0: Traversable[String] = List()

CollectionFactory[Boolean]("")
res1: Traversable[Boolean] = Set()

Answer

You need a ClassTag[A] to instantiate a new Array[A]. This is easy to fix by adding an implicit ct: ClassTag[A] parameter.

object CollectionFactory {
  def apply[A: reflect.ClassTag](s: String): Traversable[A] = {
    s match {
      case "list" => List[A]()
      case "array" => new Array[A](1)
      case _ => Set[A]()
    }
  }
}