Public functions should have an explicit return type

Prefer this:
def someF(par1: T1, par2: T2): Result = {
To this:
def someF(par1: T1, par2: T2) = {
Yeah, type inference on the result of a function is great and all, but for public methods:
  • it's not OK to rely on an IDE or to inspect the implementation in order to see the returned type
  • Scala currently infers the most specialized type possible, because in Scala the return type on functions is covariant, so you might actually get a really ugly type back
For example, what is the returned type of this function:
def sayRunnable(name: String) = new Runnable {
  def sayIt() = println(s"Hello, $name")
  def run() = sayIt()
Do you think it's Runnable? Wrong, it's Runnable{def sayIt(): Unit}.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Scala snippets
Sign Up Now
or Subscribe for future quizzes