是否可以匹配Scala中的参数类型?假设我有一个函数接收两个参数:a value和a type.我想使用模式匹配来进行类型转换.
像这样的东西:
datatype match {
case IntegerType => return value.toInt
case FloatType => return value.toFloat
case StringType => return value
case DecimalType(_,_) => return BigDecimal(value) // this is not working
case _ => return strrepr
}
Run Code Online (Sandbox Code Playgroud)
这里DecimalType接受两个参数来指定精度所需的精度.它可以是例如:
org.apache.spark.sql.types.DecimalType = DecimalType(10,2)
Run Code Online (Sandbox Code Playgroud)
我尝试了几个选项,似乎没有任何工作:
因为case DecimalType => return BigDecimal(value)我得到:
error: pattern type is incompatible with expected type;
found : org.apache.spark.sql.types.DecimalType.type
required: org.apache.spark.sql.types.DataType
Note: if you intended to match against the class, try `case DecimalType(_,_)`
Run Code Online (Sandbox Code Playgroud)因为 …