Description
On Control Structures - Using a match
expression as the body of a method:
Because
match
expressions return a value, they can be used as the body of a method.
This method takes aBoolean
value as an input parameter, and returns aString
, based on the result of thematch
expression:def isTruthy(a: Matchable) = a match case 0 | "" => false case _ => true
This method does not only take Boolean as an input, as stated by the function signature. It should work with any Matchable
value. Also, it does not contain the case false
neither the case null
scenario. I'm not sure if it is intended this way or it is an error. I imagine this function tries to mimic JavaScript's behaviour so it should consider those cases too. I added some spaces to ident the true
case as it is usually done in other other FP languages like Haskell. I'm not familiar enough with Scala, let me know if my changes are OK and i'll create a pull request
Proposed solution
Because match
expressions return a value, they can be used as the body of a method.
This method takes a Matchable
value as an input parameter, and returns a Boolean
, based on the result of the match
expression:
def isTruthy(a: Matchable) = a match
case 0 | "" | false | null => false
case _ => true
The input parameter a
is defined to be the [Matchable
type][matchable]---which is the root of all Scala types that pattern matching can be performed on.
The method is implemented by matching on the input, providing two cases:
The first one checks whether the given value is either the integer 0
, an empty string, null
or false
and returns false
in this case.
In the default case, we return true
for any other value.
These examples show how this method works:
isTruthy(0) // false
isTruthy(false) // false
isTruthy(null) // false
isTruthy("") // false
isTruthy(1) // true
isTruthy(" ") // true
isTruthy(2F) // true
Using a match
expression as the body of a method is a very common use.