【问题标题】:Pattern type is incompatible with expected type模式类型与预期类型不兼容
【发布时间】:2018-08-07 20:43:39
【问题描述】:

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

代码:

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

DoubleType 模式类型与预期类型不兼容。找到 DoubleType.type。必需:(数据类型,字符串)。

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

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 之后,为什么会出现这种模式匹配类型错误。

【问题讨论】:

    标签: scala


    【解决方案1】:

    您错过群组 inputType 和 inputColName 为 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 定义为 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 的情况下执行以下操作,那么它也是有效的(现在case 的inputType 被视为(org.apache.spark.sql.types.NumericType with Product with Serializable, String))

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

    我希望解释清楚。

    【讨论】:

    • 太棒了!如何打印出数据类型?
    • 它的 scala REPL。我只是复制粘贴。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多