0

The toArray call in following code does not compile

trait A[T] {
  def create:T
  def foo(a:Array[Int]) = {
    for(b <- a) yield create
  }.toArray
}

It throws the following errors:

not enough arguments for method toArray: (implicit evidence$1: scala.reflect.ClassTag[T])Array[T]. Unspecified value parameter evidence$1.  
No ClassTag available for T 

How do I fix it?

3 Answers 3

2

As Sergey said, Java arrays need to know the type of T, but T is eliminated by type erasure.

In scala you can "preserve" a type information at runtime using a ClassTag.

Here's a more in-depth discussion about arrays.

As per fixing it, you need to provide evidence of a ClassTag for T. Here's a possible solution:

import scala.reflect.ClassTag

trait A[T] {
  def create: T
  def foo(a: Array[Int])(implicit ev: ClassTag[T]) = {
    for(b <- a) yield create
  }.toArray
}

The implicit ev parameter is filled in automatically by the compiler.

1

The problem is that you can't create an Array[T] without knowing T. The ClassTag is Scala's way of representing this information. The simple fix would be to change trait A[T] to abstract class A[T: ClassTag] (class is needed because traits can't have any constructor parameters, including implicit ones). If you then create it with a specific type, e.g. class B extends A[Int], the compiler will insert the correct ClassTag itself, with a generic you need to pass the ClassTag through: class C[T: ClassTag] extends A[T].

1

The simplest way is to remove toArray call. Because you iterate over array so your result will be array too.

2
  • Where do I add ClassTag? Commented Jun 9, 2016 at 8:06
  • The result is of type ArraySeq. I want Array Commented Jun 9, 2016 at 8:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.