kioba
01/11/2019, 4:45 PMdef listToString(list: List[String]): String = list match {
case s :: rest => s + " " + listToString(rest)
case Nil => ""
}
would it make sense to add a similar pattern matching for the destructuring declaration?
the example above could be replaced with `fold`/`reduce` and mixing it with windowed
but if the list length is zero we would get an exception
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
with pattern matching this could be automatically run to the case Nil => ""
. The compiler also could check for unsatisfied cases just like it does right now when we match agains for enum or sealed class typesDico
01/11/2019, 6:13 PMif (list.isNotEmpty()) list.first() + " " + listToString(list.drop(1))
else ""
kioba
01/11/2019, 6:43 PMDico
01/11/2019, 9:11 PM[element1, element2, element3]
when (list) {
[first, *remaining] -> first + " " + listToString(remaining)
else -> ""
}
Keep in mind that this is highly speculative, and I personally still think it's not very readable.when (list) {
[Person("Karoly", age), *remaining] -> println(age)
}
elizarov
01/12/2019, 1:44 PMkioba
01/15/2019, 12:18 PMif(list.size > 3)
doMore(list[0], list[1], list[2])
rec (list.drop(3))
else if (list.size == 3)
do3(list[0], list[1], list[2])
else if (list.size == 2)
do2(...)
else if(list.isEmpty())
do0()
could be replaced with the following:
when(list) {
(first, second, third, rest) -> doMore(); rec(rest)
(first, second, third, null) -> do3()
(first, second, null) -> do2()
(null) -> do0()
}
I personally find it readable and helpful to check for size, and destruct the container into components. Also matching might be able to warn agains left out cases for example in my example the single element list case.Dico
01/15/2019, 12:23 PMnull
to indicate that the list ended is horrible.
Moreover, you're not using the variables in the matches, I assume you left that out.kioba
01/15/2019, 12:27 PMDico
01/15/2019, 12:31 PMelizarov
01/15/2019, 3:33 PMwhen (list.size) {
0 -> do0()
2 -> do2()
3 -> do3()
else -> { doMore(); rest(list.subList(3, list.size)) }
}
For example, this way I immediately see that the case for size=1 was forgotten.kioba
01/15/2019, 7:11 PM