简体   繁体   中英

What does case _: mean in scala

For example:

    castType match {                                                                                  
      case _: ByteType => datum.toByte  
      case _: ShortType => datum.toShort                                                              
      case _: IntegerType => datum.toInt
      case _ => throw new RuntimeException(s"Unsupported type: ${castType.typeName}") 
    }

What exactly does : do? ' ' is a placeholder and would usually mean "matching anything", but what does the ":" do? And How is the type "ByteType" treated?

case _ : ByteType => means that the matched object has to be of type ByteType

The whole match statement could also be written as a series of if statements:

if (castType.isInstanceOf[ByteType]) {
   datum.toByte
} else if (castType.isInstanceOf[....
...

But that would be quite ugly, wouldn't it?

Some of the comments on the above answer are actually helpful unlike the answer itself.

case _ : ByteType is like if (castType.isInstanceOf[ByteType]) while case ByteType is like (castType == ByteType)

This way of writing case is specially helpful in DecimalTypes where precision could vary.

case _: DecimalType =>

For example, see SchemaConverters

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM