Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does case _: mean in scala

Tags:

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?

like image 425
EugeneMi Avatar asked Jun 10 '15 21:06

EugeneMi


People also ask

What does => mean in Scala?

=> 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).

Why do we use case class in Scala?

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.

What is case class and pattern matching Scala?

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.

What is the default option in a match case in Scala?

getList("instance").


2 Answers

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

like image 197
Abhinandan Dubey Avatar answered Sep 19 '22 07:09

Abhinandan Dubey


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?

like image 45
Gregor Raýman Avatar answered Sep 20 '22 07:09

Gregor Raýman