Reputation: 117
i'm new to scala and trying some handson exercises .
i'm trying to use implicits by placing implicits in a companion object . however , the compiler doesn't detect implicit unless it is used .
class ImplicitTest {
import Implicits.implicitInt;
println(implicitInt)
def implicitm1(implicit i : Int) = 1
println(implicitm1)
}
object Implicits {
implicit val implicitInt = 1
}
This compiles fine . However if i comment out the third line
\\println(implicitInt)`
then i get a compile-time errors on
println(implicitm1)`
which says
could not find implicit value for parameter i:Int`
not enough arguments for method implicit m1(implicit i:Int) . Unspecified value parameter i`
what did i do wrong here ?
Thanks in advance
Upvotes: 3
Views: 81
Reputation: 435
Another solution is to move the object Implicits definition above the class ImplicitTest.
In this case the type for implicitInt is already inferred.
Upvotes: 0
Reputation: 170713
If you include the type for val implicitInt: Int = 1
, it works. Issues like this are one of the reasons it's recommended to always specify types for implicits.
Scala type inference works from top to bottom, so in your case the compiler doesn't yet know this type when it gets to typechecking the println(implicitm1)
line.
I guess that when you include println(implicitInt)
, the compiler is forced to find implicitInt
's type at that line.
Upvotes: 4