Created
August 19, 2016 16:50
-
-
Save vascorsd/22e65e38b08d9335422dadab52846cad to your computer and use it in GitHub Desktop.
Trying a bunch of different matches and patterns on Lists.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val emptySeq1 = Seq.empty[String] | |
val emptySeq2 = Seq[String]() | |
val someSeq1 = Seq("one") | |
val someSeq2 = Seq("one", "two") | |
// good matches a list with something, no matter the size, works by making sure the strictly empty | |
// is matched FIRST | |
def test1(s: Seq[String]) = s match { | |
case errs @ Seq() => "got empty" | |
case _ => "got some" | |
} | |
// bad, misses case of more than one in the list | |
def test2(s: Seq[String]) = s match { | |
case errs @ Seq(_) => "got some" | |
case _ => "got empty" | |
} | |
// bad, misses case of more than one in the list | |
def test3(s: Seq[String]) = s match { | |
case errs @ _ :: Nil => "got some" | |
case _ => "got empty" | |
} | |
// bad, misses case of more than one in the list | |
def test4(s: Seq[String]) = s match { | |
case errs @ _ :: Nil => "got some" | |
case Nil => "got empty" | |
} | |
// good matches a list with something, no matter the size | |
def test5(s: Seq[String]) = s match { | |
case errs @ _ :: _ => "got some" | |
case Nil => "got empty" | |
} | |
// pretty much the same as test5, but "hardcoded" to just work on Seqs | |
def test6(s: Seq[String]) = s match { | |
case errs @ Seq(_, _*) => "got some" | |
case Seq() => "got empty" | |
} | |
test1(emptySeq1) | |
test1(emptySeq2) | |
test1(someSeq1) | |
test1(someSeq2) | |
test2(emptySeq1) | |
test2(emptySeq2) | |
test2(someSeq1) | |
test2(someSeq2) | |
test3(emptySeq1) | |
test3(emptySeq2) | |
test3(someSeq1) | |
test3(someSeq2) | |
test4(emptySeq1) | |
test4(emptySeq2) | |
test4(someSeq1) | |
//test4(someSeq2) match error, missing case for handling n elements | |
test5(emptySeq1) | |
test5(emptySeq2) | |
test5(someSeq1) | |
test5(someSeq2) | |
test6(emptySeq1) | |
test6(emptySeq2) | |
test6(someSeq1) | |
test6(someSeq2) | |
// Conclusion: I prefer style of test5 or test6 as they are exhaustive and doesn't | |
// care about the matching order, so adapatable to be changed without thinking much about it | |
// on specific cases. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment