模式类型与预期类型不兼容

时间:2018-02-28 03:42:08

标签: scala

我已经阅读了其他相关问题,但我没有得到答案。

代码:

inputType.zip(inputColName).zipWithIndex.map {
  case (inputType, inputColName, idx) =>
    inputType match {
      case **DoubleType** => println("test1")
      case _ => println('test2 ')
    }
}

DoubleType模式类型与预期类型不兼容。找到DoubleType.type。必需:(DataType,String)。

我尝试了两个简化版本,语法看起来正确。

List(1,2,3).zip(List(4,5,6)).map { case(a, b) => 
        a match {case 1 => println(s"First is $a, second is $b") 
                 case _ => println("test")}}

以下也适用

inputType.zipWithIndex.map {
  case (inputType, idx) =>
    inputType match {
      case DoubleType => println("test1")
      case _ => println('test2 ')
    }
}

我不明白为什么在添加zip之后,为什么我有这种模式匹配类型错误。

1 个答案:

答案 0 :(得分:5)

您错过了群组 inputTypeinputColName tuple2

inputType.zip(inputColName).zipWithIndex.map {
  case ((inputType, inputColName), idx) =>
    inputType match {
      case DoubleType => println("test1")
      case _ => println("test2")
    }
}

当您使用zip作为

inputType.zip(inputColName)

然后 Scala编译器会将其视为

List[(org.apache.spark.sql.types.NumericType with Product with Serializable, String)]

当你添加.zipWithIndex时, Scala编译器将把它读作

List[((org.apache.spark.sql.types.NumericType with Product with Serializable, String), Int)]

问题

当您将案例定义为case(inputType, inputColName, idx)时, Scala编译器会将inputType视为(org.apache.spark.sql.types.NumericType with Product with Serializable, String)inputColName为您创建Int时形成的((org.apache.spark.sql.types.NumericType with Product with Serializable, String), Int) dataTypes inputType.zip(inputColName).zipWithIndex。所以永远不会发现idx

即使您在没有idx的情况下执行以下操作,也有效(现在inputType的{​​{1}}被视为case

(org.apache.spark.sql.types.NumericType with Product with Serializable, String)

我希望解释清楚。

相关问题