Suppose I have
def foo(x: Any) = x match {
case s: String => println(0)
case i: Int => println(1)
case l: Long => println(2)
//...
}
Is there any way to make something like the following?
def foo(x: Any) = x match {
case s: String => println(0)
case i: Numeric => println("Numeric")
}
The match keyword provides a convenient way of applying a function (like the pattern matching function above) to an object. Try the following example program, which matches a value against patterns of different types.
Case classes are Scala's way to allow pattern matching on objects without requiring a large amount of boilerplate. In the common case, all you need to do is add a single case keyword to each class that you want to be pattern matchable.
Matches any number (or none) of the single character that immediately precedes it. For example, bugs* will match bugs (one s ) or bug (no s 's). The character preceding the * can be one that is specified by a regular expression. For example, since . (dot) means any character, .
C# pattern matching is a feature that allows us to perform matching on data or any object. We can perform pattern matching using the is expression and switch statement. is expression is used to check, whether an object is compatible with given type or not. In the following example, we are implementing is expression.
You could try this:
def foo[A](x: A)(implicit num: Numeric[A] = null) = Option(num) match {
case Some(num) => println("Numeric: " + x.getClass.getName)
case None => println(0)
}
Then this
foo(1)
foo(2.0)
foo(BigDecimal(3))
foo('c')
foo("no")
will print
Numeric: java.lang.Integer
Numeric: java.lang.Double
Numeric: scala.math.BigDecimal
Numeric: java.lang.Character
0
Note that obtaining a null
implicit parameter would not mean that no such implicit exist, but just that none was found at compile time in the search scope for implicits.
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