Why would I use -Wself-implicit in Scala 2.13?

Originally asked on reddit:

In Scala 2.13 I see this compiler option

-Wself-implicit                Warn when an implicit resolves to an enclosing self-definition.

Why would I care about this? That is, what potential issue is it warning me about?

I tried cross compiling one of our projects at work and some things like scala.io.Source.fromBytes fail to compile because the implicit Codec instance was apparently a self-definition (in a supertrait of the Codec companion). Similarly ScalaTests using any of their implicit-based DSL fail to compile because many of those implicits are in mixin traits.

It seems like this warns about a very common practice for placing implicits to be found naturally and orderly, including in the standard library. So why would I ever use it? Is there a problem with such implicits or a principle that is violated?

Should I want to use the option eventually, is there a workaround where I can make such self-implicits be found in a way that doesn’t trigger the warning so I can still use libraries making use of the feature? Creating a new implicit value and referencing the value from the supertrait works but could get tedious quickly. Maybe the point is to have explicit local values/def/imports?

1 Like

It’s supposed to defend against actual bugs like in

implicit val foo: Foo = implicitly[Foo]

foo will be null here because its definition is actually recursive. You should care about that.

However there appears to be a bug (https://github.com/scala/bug/issues/11813) with this warning, which might be why you think that it does something useless. It should be fixed in the next Scala release.

Ah, okay, that makes sense. I was having a hard time imagining what the flag was trying to detect and that bug does indeed look like the root of my issue. Thanks.