What is the returned type of this function:
def sayHelloRunnable(name: String) = new Runnable {
  def sayIt() = println(s"Hello, $name")
  def run() = sayIt()
}
Explanation
It is a good practice to have an explicit return type for public methods.
Because you could think that returned type is Runnable? Wrong, it's Runnable{def sayIt(): Unit}.
As a side-effect, this also increases compilation times, as whenever sayHelloRunnable changes implementation, it also changes the signature so everything that depends on it must be recompiled.
Theory
  • 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}.

Слідкуй за CodeGalaxy

Мобільний додаток Beta

Get it on Google Play
Зворотній Зв’язок
Продовжуйте вивчати
тести з Scala
Cosmo
Зареєструйся Зараз
або Підпишись на майбутні тести