Scala Expert · Lesson 1 · On the house

ClassTag

Runtime arrays, ClassTag, implicitly, Array.newBuilder. Lesson 1 is free — on the house.

Lessons · Scala Expert · Lesson 1 of 10 · On the house

ClassTag

Runtime arrays, ClassTag, implicitly, Array.newBuilder.

Illustration for Scala
Lesson 1 is on the house.

JVM arrays need a concrete element class at runtime. Erasure deletes A from def tabulate[A](n: Int)(f: Int => A): Array[A], so the compiler demands a ClassTag[A] — evidence of A's runtime class.

Context-bound form: def tabulate[A: ClassTag](n: Int)(f: Int => A): Array[A] = Array.tabulate(n)(f). Desugars to an implicit ClassTag[A]. Summon with implicitly[ClassTag[A]] (Scala 2).

Array.newBuilder[A] also needs a ClassTag. Prefer builders when you grow length unknown up front; result() yields the array. classTag[A].runtimeClass exposes the Class[_].

Manifest is the older API — prefer ClassTag / TypeTag in modern Scala 2. ClassTag is enough for arrays; it does not reify higher-kinded or path-dependent structure (that is TypeTag).

Misses: writing new Array[A](n) without a ClassTag in scope, assuming List needs ClassTag (it does not — lists box on the heap), or confusing ClassTag with ClassTag for primitives only (it works for any concrete A).

classtag

import scala.reflect.ClassTag

object ClassTagDemo {
  def tabulate[A: ClassTag](n: Int)(f: Int => A): Array[A] =
    Array.tabulate(n)(f)

  def collectSome[A: ClassTag](xs: List[Option[A]]): Array[A] = {
    val b = Array.newBuilder[A]
    xs.foreach {
      case Some(a) => b += a
      case None    => ()
    }
    b.result()
  }

  def main(args: Array[String]): Unit = {
    val ints = tabulate(4)(i => i * i)
    println(ints.mkString(","))
    val tag = implicitly[ClassTag[String]]
    println(tag.runtimeClass.getSimpleName)
    val arr = collectSome(List(Some("a"), None, Some("b")))
    println(arr.mkString(","))
  }
}
Match this when you type.

Quiz

Why does Array.tabulate[A] need a ClassTag[A]?

Quiz

What does implicitly[ClassTag[String]] summon?

Quiz

When is Array.newBuilder[A] useful?

Quiz

Does List[A].map need a ClassTag?

Check

Match the still for: ClassTag.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.