Reputation: 3070
In scala we can pattern match on types. So is it possible to bind a variable to the matched pattern with the type. Right now the bounded variable has type Any
val a: Any = "hello"
a match {
case v @ String {
v.length() // not working
}
}
Upvotes: 0
Views: 349
Reputation: 1291
To pattern match on a type follow the syntax exposed in @chengpohi .
The bind operator @
is used to refer to a (sub)structure of the data extracted in pattern matching. For example in
("hello",123) match {
case t @ (fst: String, snd: Int) => println(s"got tuple $t")
case _ =>
}
label t
refers to the entire tuple, not having to denote fst
and snd
.
Upvotes: 0
Reputation: 14227
Your syntax is not correct!!!, it should be like:
val a: Any = "hello"
a match {
case v: String => v.length()
}
use :
to match type, and =>
with the next block
Upvotes: 4