无法从类中返回数组

时间:2016-11-30 20:23:18

标签: arrays scala types

试图理解'申请'方法。我想创建一个类,它返回List,Array或Set,具体取决于传递的参数。该代码适用于List和Set,但不适用于Array。我无法理解这个问题

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()

1 个答案:

答案 0 :(得分:0)

您需要ClassTag[A]来实例化新的Array[A]。通过添加implicit ct: ClassTag[A]参数可以轻松解决此问题。

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]()
    }
  }
}