case _是什么意思:scala中的意思

Eug*_*eMi 7 scala

例如:

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

到底是什么:做什么?' '是一个占位符,通常意味着"匹配任何东西",但":"是做什么的?如何处理"ByteType"类型?

Gre*_*man 8

case _ : ByteType => 表示匹配的对象必须是类型 ByteType

整个match陈述也可以写成一系列if陈述:

if (castType.isInstanceOf[ByteType]) {
   datum.toByte
} else if (castType.isInstanceOf[....
...
Run Code Online (Sandbox Code Playgroud)

但那会很难看,不是吗?

  • `case ByteType =>`是不同的东西.检查与对象`ByteType`的相等性.所以`case _:ByteType`就像`if(castType.isInstanceOf [ByteType])`.`case ByteType`就像`(castType == ByteType)`.您可以使用哪种变体取决于`ByteType`实际上是什么.它是一种类型还是一种物体? (2认同)