Define the following code:
import scala.collection.JavaConversions._
val iter:java.util.Iterator[Any] = Array[Any](1, 2, 3).iterator
def func(a:Any):String = a.toString
def test[T:ClassManifest](iter:java.util.Iterator[Any], func:Any=>T):Array[T] =
iter.map(i=>func(i)).toArray
def testFunc = test(iter, func)
Here, I need to use ClassManifest
for it to compile correctly, otherwise I get the error:
scala> def test[T](iter:java.util.Iterator[Any], func:Any=>T):Array[T] =
| iter.map(i=>func(i)).toArray
<console>:11: error: could not find implicit value for evidence parameter of
type ClassManifest[T]
iter.map(i=>func(i)).toArray
^
On the other hand, the alternate code below using List
does not require this and compiles fine.
import scala.collection.JavaConversions._
val iter:java.util.Iterator[Any] = Array[Any](1, 2, 3).iterator
def func(a:Any):String = a.toString
def test1[T](iter:java.util.Iterator[Any], func:Any=>T):List[T] =
iter.map(i=>func(i)).toList
def testFunc1 = test1(iter, func).toArray
Note that the final output of testFunc
and testFunc1
are identical.
How come the List
version does not require a ClassManifest
?