In the code snippet included below, I have a recursive function call, used to facilitate a retry if a network call fails (Amazon SimpleDB will occasionally return a 503 and require retry.)
When I try to compile, the Scala complains recursive method simpledb_update needs result type.
// sends data to SimpleDB. Retries if necessary
def simpledb_update(name: String, metadata: Map[String,String], attempt: Int) = {
try {
db(config("simpledb_db")) += (name, metadata)
} catch {
case e =>
// if it fails, try again up to 5 times
if(attempt < 6)
{
Thread.sleep(500)
simpledb_update(name, metadata, attempt + 1)
} else
AUlog(name + ": SimpleDB Failed")
}
}
Why is this required on recursive functions? My thought is to just return a true/false boolean to satisfy the compiler… the following compiles fine.
// sends data to SimpleDB. Retries if necessary
def simpledb_update(name: String, metadata: Map[String,String], attempt: Int): Boolean = {
try {
db(config("simpledb_db")) += (name, metadata)
true
} catch {
case e =>
// if it fails, try again up to 5 times
if(attempt < 6)
{
Thread.sleep(500)
simpledb_update(name, metadata, attempt + 1)
} else
AUlog(name + ": SimpleDB Failed")
false
}
}
As I understand it, recursive functions need a return type because the type inference algorithm is not powerful enough to determine return types for all recursive functions.
However, you don’t need to make up a return type, you just need to declare the return type you were already using: Unit. Unit is a special type with only one element (). It’s also the type of most “statements” in Scala, and is the return type to declare for methods that don’t need to return anything, but are executed only for their side-effects (as yours is). You can either declare your method as returning unit as you would other types
More idiomatically Scala provides a special syntax for Unit-returning methods, just leave off the return type and the equals signAccording to scala style guide you should prefer to use equal sign
http://docs.scala-lang.org/style/declarations.html