Abuse of match?

后端 未结 2 378
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-02 22:53

Would you consider the following block of code match abuse and if so what\'s a more elegant way to do it without a big if-else-if block?

def sum(base: Int, x         


        
2条回答
  •  情话喂你
    2021-01-02 23:14

    No. Why abuse? It's fairly readable IMO...

    The problem I see is that money match ... is fairly arbitrary (you only use the direct pattern in the first case); a complete "abuse" would start like

    () match {
      case _ if (money == 0) => 1
      ...
    

    So perhaps stick to if-else; you can combine the second and third condition (if( money < 0 || coins.isEmpty ) ...)


    Also note that although you "know" in the end that coins is not empty and thus may "safely" call head and tail on it, this is a typical source of unexpected runtime errors. The advantage of coins match { case Nil => ...; case head :: tail => ...} is that you cannot make such a mistake.

提交回复
热议问题