在List中查找数据类型

时间:2017-03-07 11:18:43

标签: scala apache-spark

我有一个要求,我需要根据List的数据类型执行一些转换。让我们说如果我得到List[String]我需要应用一些转换,但如果我得到List[Int],则需要应用一些不同的转换。我已经定义了一个函数,它将使用List[Any]和匹配语句我需要检查数据类型。我尝试使用isInstanceOf,但它没有成功。

如何检查List的数据类型。

1 个答案:

答案 0 :(得分:2)

假设您的列表在其所有元素中具有相同的类型并使用普通Scala,您可以执行以下操作:

def test(list: List[Any]): List[Any] = {
  if(list.isEmpty) return List()
  list.head match {
    case a: String => list.map(str => str.asInstanceOf[String]+"3")
    case a: Int => list.map(int => int.asInstanceOf[Int]+3)
  }
}

这不是最好的解决方案,但如果没有不同的图书馆我就无法看到其他任何内容

这里甚至是更奇怪的解决方案,它允许您返回与此功能完全相同的类型,当然您需要在列表的每个元素中具有完全相同的类型:

def test[T](list: List[T]): List[T] = {
  if(list.isEmpty) return List()
  list.head match {
    case a: String => list.map(str => (str.asInstanceOf[String]+"3").asInstanceOf[T])
    case a: Int => list.map(int => (int.asInstanceOf[Int]+3).asInstanceOf[T])
  }
}

test(List("123","123")) // res0: List[String] = List(1233, 1233)
test(List(1,2,3)) // res1: List[Int] = List(4, 5, 6)

再次编辑,最后但并非最不重要的是,您可以使用TypeTag来避免类型擦除和检查列表类型,如下所示:

def test1[T: TypeTag](list: List[T]): List[T] = typeOf[T] match {
  case t if t =:= typeOf[String] => list.map(str => (str.asInstanceOf[String]+"3").asInstanceOf[T])
  case t if t =:= typeOf[Int] => list.map(int => (int.asInstanceOf[Int]+3).asInstanceOf[T])
  case _ => list
}

test1(List("123", "123", "123")) // Strings so: res0: List[String] = List(1233, 1233, 1233)
test1(List("123","123", 1)) // Oh-oh we have not defined type, so: res1: List[Any] = List(123, 123, 1)
test1(List(1,2,3)) // And here we have res2: List[Int] = List(4, 5, 6)