Luigi Plinge
Luigi Plinge

Reputation: 51109

Implicit vals in traits behave differently with type annotation

Just wondering if the following is a bug or a feature:

Welcome to Scala version 2.10.0-M3 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0).
Type in expressions to have them evaluated.
Type :help for more information.

scala> class TypeClass[T]
defined class TypeClass

scala> trait A[T] {
     |   implicit val t = implicitly[TypeClass[T]]
     | }
<console>:9: error: could not find implicit value for parameter e: TypeClass[T]
         implicit val t = implicitly[TypeClass[T]]
                                    ^

As expected, this doesn't compile because there's no constraint on T. But when I add a type annotation it compiles:

scala> trait A[T] {
     |   implicit val t: TypeClass[T] = implicitly[TypeClass[T]]
     | }
defined trait A

Shouldn't the compiler be complaining here? Why should a type annotation make a difference? If we instantiate something with this trait, t is null.

Upvotes: 1

Views: 190

Answers (2)

Kaito
Kaito

Reputation: 1765

I'd say it's neither bug nor feature, just a consequence of some features.

In the first example, there is no implicit value of type TypeClass[T] in scope. You rely on type inference to know the type of t and since implicits are resolved at compile time, the type of t is not defined because the implicit value can't be found.

In the second example there is a suitable implicit value in scope, namely t. If you did not allow that behavior in general you couldn't do recursive definitions like:

val fibs: Stream[Int] = 0 #:: 1 #:: fibs.zip(fibs.tail).map{case (x,y) => x+y}

Upvotes: 2

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297205

Actually, you are just scr**ing yourself here. :-)

You just declared that the implicit TypeClass[T] is val t. That is, val t = t, which makes it null. Ouch!

T is abstract, so the compiler cannot provide a TypeClass for it. You'd have to get that with the T parameter, but you won't be able to in a trait. In a class, make it T : TypeClass.

Upvotes: 5

Related Questions