[英]scala match Class[X] works only with class defined outside case
I'm working with scala to transform different java types to Spark DataType, so I wrote the following method: 我正在与scala一起将不同的Java类型转换为Spark DataType,因此我编写了以下方法:
def convertDataType(x : Class[_]): DataType = {
x match {
case i: Class[Integer] => IntegerType
case s: Class[String] => StringType
case d: Class[Double] => DoubleType
case l: Class[Long] => LongType
case s: Class[Short] => ShortType
case b: Class[Byte] => ByteType
case f: Class[Float] => FloatType
case ab: Class[Array[Byte]] => BinaryType
case bl: Class[Boolean] => BooleanType
case ts: Class[Timestamp] => TimestampType
case dt: Class[Date] => DateType
case _ => StringType
}}
However, with an input x (java.lang.String), it breaks out with a IntegerType. 但是,使用输入x(java.lang.String),它会以IntegerType开头。 I tried another way:
我尝试了另一种方式:
def convertDataType(x : Class[_]): DataType = {
val S = classOf[String]
val I = classOf[Integer]
val D = classOf[Double]
val L = classOf[Long]
val SH = classOf[Short]
val B = classOf[Byte]
val F = classOf[Float]
val AB = classOf[Array[Byte]]
val BL = classOf[Boolean]
val TS = classOf[Timestamp]
val DT = classOf[Date]
x match {
case I => IntegerType
case S => StringType
case D => DoubleType
case L => LongType
case SH => ShortType
case B => ByteType
case F => FloatType
case AB => BinaryType
case BL => BooleanType
case TS => TimestampType
case DT => DateType
case _ => StringType
}}
The second way worked well and return the StringType as expected. 第二种方法运行良好,并按预期返回StringType。 I have no idea what's wrong in the first implementation?
我不知道第一个实现有什么问题?
Thanks a lot. 非常感谢。
Matching : Class[Double]
is exactly the same as matching : Class[_]
because the generic type parameters aren't available. Matching
: Class[Double]
与Matching : Class[_]
完全相同,因为没有通用类型参数。 The compiler actually should warn you about it: 编译器实际上应该警告您:
warning: non variable type-argument Double in type pattern java.lang.Class[Double] is unchecked since it is eliminated by erasure
This also happens for any other generic type except Array
s. 除
Array
之外的任何其他泛型类型也会发生这种情况。 There are a lot of Stack Overflow questions and articles about this, search for "type erasure". 关于此的堆栈溢出问题和文章很多,请搜索“类型擦除”。
In the second case, you are doing something entirely different: comparing values instead of checking types. 在第二种情况下,您要做的事情完全不同:比较值而不是检查类型。 This doesn't run into the above problem.
这不会遇到上述问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.