@@ -26,33 +26,36 @@ object HiveTypeCoercion {
2626 // See https://cwiki.apache.org/confluence/display/Hive/LanguageManual+Types.
2727 // The conversion for integral and floating point types have a linear widening hierarchy:
2828 private val numericPrecedence =
29- Seq (ByteType , ShortType , IntegerType , LongType , FloatType , DoubleType , DecimalType .Unlimited )
29+ IndexedSeq (
30+ ByteType ,
31+ ShortType ,
32+ IntegerType ,
33+ LongType ,
34+ FloatType ,
35+ DoubleType ,
36+ DecimalType .Unlimited )
3037
3138 /**
3239 * Find the tightest common type of two types that might be used in a binary expression.
3340 * This handles all numeric types except fixed-precision decimals interacting with each other or
3441 * with primitive types, because in that case the precision and scale of the result depends on
3542 * the operation. Those rules are implemented in [[HiveTypeCoercion.DecimalPrecision ]].
3643 */
37- def findTightestCommonType (t1 : DataType , t2 : DataType ): Option [DataType ] = {
38- val valueTypes = Seq (t1, t2).filter(t => t != NullType )
39- if (valueTypes.distinct.size > 1 ) {
40- // Promote numeric types to the highest of the two and all numeric types to unlimited decimal
41- if (numericPrecedence.contains(t1) && numericPrecedence.contains(t2)) {
42- Some (numericPrecedence.filter(t => t == t1 || t == t2).last)
43- } else if (t1.isInstanceOf [DecimalType ] && t2.isInstanceOf [DecimalType ]) {
44- // Fixed-precision decimals can up-cast into unlimited
45- if (t1 == DecimalType .Unlimited || t2 == DecimalType .Unlimited ) {
46- Some (DecimalType .Unlimited )
47- } else {
48- None
49- }
50- } else {
51- None
52- }
53- } else {
54- Some (if (valueTypes.size == 0 ) NullType else valueTypes.head)
55- }
44+ val findTightestCommonType : (DataType , DataType ) => Option [DataType ] = {
45+ case (t1, t2) if t1 == t2 => Some (t1)
46+ case (NullType , t1) => Some (t1)
47+ case (t1, NullType ) => Some (t1)
48+
49+ // Promote numeric types to the highest of the two and all numeric types to unlimited decimal
50+ case (t1, t2) if Seq (t1, t2).forall(numericPrecedence.contains) =>
51+ val index = numericPrecedence.lastIndexWhere(t => t == t1 || t == t2)
52+ Some (numericPrecedence(index))
53+
54+ // Fixed-precision decimals can up-cast into unlimited
55+ case (DecimalType .Unlimited , _ : DecimalType ) => Some (DecimalType .Unlimited )
56+ case (_ : DecimalType , DecimalType .Unlimited ) => Some (DecimalType .Unlimited )
57+
58+ case _ => None
5659 }
5760}
5861
0 commit comments