Be careful when you want to sue Return in Scala:
/ Add two ints, and use this method to sum a list
def add(n:Int, m:Int): Int = n + m
def sum(ns: Int*): Int = ns.foldLeft(0)(add)
scala> sum(33, 42, 99)
res0: Int = 174
// Same, using return
def addR(n:Int, m:Int): Int = return n + m
def sumR(ns: Int*): Int = ns.foldLeft(0)(addR)
scala> sumR(33, 42, 99)
res1: Int = 174
// Inline add and addR
def sum(ns: Int*): Int = ns.foldLeft(0)((n, m) => n + m) // inlined add
scala> sum(33, 42, 99)
res2: Int = 174 // alright
def sumR(ns: Int*): Int = ns.foldLeft(0)((n, m) => return n + m) // inlined addR
scala> sumR(33, 42, 99)
res3: Int = 33 // um.
Source: https://tpolecat.github.io/2014/05/09/return.html
Comments
Post a Comment