Skip to content

implicits defined in companion object cannot be found in classes, order matters #8748

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
scabug opened this issue Jul 25, 2014 · 3 comments
Closed

Comments

@scabug
Copy link

scabug commented Jul 25, 2014

If I define a typeclass in a class's companion object and use it in the class, like this:

// Util.scala
class Util {
	import Util._

	val reading = implicitly[Read[Int]].read("100")
}

object Util {
	sealed trait Read[T] {
		def read(s: String): T
	}

	implicit object IntRead extends Read[Int] { def read(s: String) = s.toInt }
}

The following compilation error is fired:

error: could not find implicit value for parameter e: Util.Read[Int]
val reading = implicitly[Read[Int]].read("100")

But if the object is defined before the class, it works OK.

// Util.scala
object Util {
	sealed trait Read[T] {
		def read(s: String): T
	}

	implicit object IntRead extends Read[Int] { def read(s: String) = s.toInt }
}

class Util {
	import Util._

	val reading = implicitly[Read[Int]].read("100")
}

I'm not sure whether this is an intended behaviour? But it doesn't feel right since it shouldn't matter to the developer the order of class and its companion object.

Note that these also happens for traits.

@scabug
Copy link
Author

scabug commented Jul 25, 2014

Imported From: https://issues.scala-lang.org/browse/SI-8748?orig=1
Reporter: Shiva Wu (shivawu)
Affected Versions: 2.11.1
Duplicates #8697

@scabug
Copy link
Author

scabug commented Jul 25, 2014

@gourlaysama said:
This is a duplicate of #8697.

See the comments in the ticket: it might not be possible to change this behavior...

@scabug scabug closed this as completed Jul 25, 2014
@scabug
Copy link
Author

scabug commented Jul 25, 2014

Shiva Wu (shivawu) said:
Yeah, these two issues do look similar.
But I think they're a bit different in the sense that, in #8697, it's two objects.
but In this issue, it turns out to be the trait and its companion object.

I kind of get the impression that the trait should be defined before its companion object, at least in usual scala code style.
But if this issue exists, it violates this code style.

Moreover, in this issue and in #8697, the implicit can not be found even after it has been imported into the scope.
This is kind of a bummer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant