Manu Chadha Manu Chadha - 1 year ago 113
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" => {
//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()

res0: Traversable[String] = List()

res1: Traversable[Boolean] = Set()

Answer Source

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]()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download