0

Here's two piece of example code, found here:

scala> val im = m.reflect(new C)
im: reflect.runtime.universe.InstanceMirror = instance mirror for C@3442299e

and here:

scala> def mkArray[T : ClassTag](elems: T*) = Array[T](elems: _*)

the first piece of code uses a method defined in scala.reflect.api.Mirrors (found here):

abstract def reflect[T](obj: T)(implicit arg0: ClassTag[T]): Universe.InstanceMirror

if you notice, there's a ClassTag used like ClassTag[T] and one used like ClassTag. What's the reason for the difference?

  • `[T : ClassTag]` is synthactic sugar for the other: http://stackoverflow.com/questions/2982276/what-is-a-context-bound-in-scala – Kolmar May 14 '15 at 17:39

1 Answers1

2

For the most part, both are equivalent.

foo[T: ClassTag]()

is syntactic sugar for

 foo[T]()(implicit ct: ClassTag[T]

However, the difference between these signatures is that in the former, you have to access the ClassTag via implicitly[ClassTag[T]] while in the latter, you can just use ct

Syntax change note: Before 2.10.x it used to not be possible to have have both a context bound like ClassTag and an implicit argument list, such as:

foo[T: ClassTag]()(implicit ex: ExecutionContext)

The error used to be reported as "Error: cannot have both implicit parameters and context bounds". IntelliJ 13 was still reporting it as late as 2.10.4, but is now accepted by the scala compiler.

Arne Claassen
  • 14,088
  • 5
  • 67
  • 106
  • The second statement isn't true. The compiler will place the context-bound arguments before the other implicit parameters. `foo[T: ClassTag]()(implicit ex: ExecutionContext)` becomes `foo[T]()(implicit evidence$1: ClassTag[T], ex: ExecutionContext)` – Michael Zajac May 14 '15 at 19:27
  • Interesting this must be a left over from a previous version of scala. Used to get `cannot have both implicit parameters and context bounds` and IntelliJ 13 still reports this in its syntax parser with 2.10.4. But sbt is happy with the syntax – Arne Claassen May 14 '15 at 19:31
  • 1
    Appears to be fixed in 14: https://youtrack.jetbrains.com/issue/SCL-6989. I believe this was added in Scala 2.10. – Michael Zajac May 14 '15 at 19:42