nrinaudo / scala-best-practices

Collection of best practices for the Scala programming language

Home Page:https://nrinaudo.github.io/scala-best-practices/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Mistake in «Add explicit type annotations to public members»?

poslegm opened this issue · comments

Rule description contains this code:

abstract class Foo {
  def getOpt[A](a: A): Option[A]
}

class FooImpl  {
  // The return type is still Option[A]
  def getOpt[A](a: A) = None
}

I thought that extends Foo was forgotten and tried to evaluate it. That's what I got:

Welcome to the Ammonite Repl 1.6.0
(Scala 2.12.8 Java 1.8.0_192)
If you like Ammonite, please support our development at www.patreon.com/lihaoyi
@ abstract class Foo {
    def getOpt[A](a: A): Option[A]
  } 
defined class Foo

@ class FooImpl extends Foo {
    // The return type is still Option[A]
    override def getOpt[A](a: A) = None
  } 
defined class FooImpl

@ val x = new FooImpl().getOpt("wow") 
x: None.type = None

Return type of getOpt is not Option[A]!

With explicit type annotation I got this:

@ class FooImpl extends Foo {
    // The return type is still Option[A]
    override def getOpt[A](a: A): Option[A] = None
  } 
defined class FooImpl

@ new FooImpl().getOpt(1) 
res6: Option[Int] = None

Oh wow. Good catches:

  • me forgetting extends Foo
  • me actually being wrong about that exception to the rule!

It's still true when you treat FooImpl as a Foo:

λ> (new FooImpl(): Foo).getOpt(1)
res6: Option[Int] = None

But I don't know if it's still worth considering this an exception to the rule...

Fixed in #17, could you take a quick look and confirm that I addressed all of your issues?

I think that now rule is correct. Thank you for quick fix!