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?
=> is the "function arrow". It is used both in function type signatures as well as anonymous function terms. () => Unit is a shorthand for Function0[Unit] , which is the type of functions which take no arguments and return nothing useful (like void in other languages).
The one of the topmost benefit of Case Class is that Scala Compiler affix a method with the name of the class having identical number of parameters as defined in the class definition, because of that you can create objects of the Case Class even in the absence of the keyword new.
Scala's pattern matching statement is most useful for matching on algebraic types expressed via case classes. Scala also allows the definition of patterns independently of case classes, using unapply methods in extractor objects.
getList("instance").
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
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With