Following 'case' syntax is used to test the type of a variable.
Syntax
case <identifier> : <type> => {.....}
scala> var x : Any = 10
var x: Any = 10
scala> var result = x match{
| case someVar:Integer => {"Integer"}
| case someVar:String => {"String"}
| case someVar:AnyRef => {"AnyRef"}
| case _ =>{"Any"}
| }
var result: String = Integer
scala> print(result)
Integer
You can even use _ as a placeholder for the identifier.
scala> var x:Any = "Hello World"
var x: Any = Hello World
scala> var result = x match{
| case _:Integer => {"Integer"}
| case _:String => {"String"}
| case _:AnyRef => {"AnyRef"}
| case _ =>{"Any"}
| }
var result: String = String
Find another example.
scala> var x:Any = new Object
var x: Any = java.lang.Object@c725dfa
scala> var result = x match{
| case _:Integer => {"Integer"}
| case _:String => {"String"}
| case _:AnyRef => {"AnyRef"}
| case _ =>{"Any"}
| }
var result: String = AnyRef
scala> print(result)
AnyRef
Variable whose type you are matching must be a base type, else scrutinee error will be thrown by Scala.
scala> var x:Integer = 10
var x: Integer = 10
scala> var result = x match{
| case someVar:Integer => {"Integer"}
| case someVar:String => {"String"}
| case someVar:AnyRef => {"AnyRef"}
| case _ =>{"Any"}
| }
|
case someVar:String => {"String"}
^
On line 3: error: scrutinee is incompatible with pattern type;
found : String
required: Integer
As you see in the above example, I define a variable ‘x’ is of type integer, but I am trying to match x with incompatible type String, so Scala compiler throws error.
To resolve the above error, define variable ‘x’ with type Any.
scala> var x:Any = 10
var x: Any = 10
scala> var result = x match{
| case someVar:Integer => {"Integer"}
| case someVar:String => {"String"}
| case someVar:AnyRef => {"AnyRef"}
| case _ =>{"Any"}
| }
var result: String = Integer
No comments:
Post a Comment