Reputation: 1845
I have this method:
private def doSomeStringProcessing[T](input: String, typeConverter: String => T): Array[T] = {
cleanTheString(input)
.split(",").map(typeConverter)
}
which gives the error:
error: type mismatch;
[INFO] found : scala.collection.mutable.ArraySeq[T]
[INFO] required: Array[T]
Per some googling, found posts saying to use the ClassManifest. Tried that and it was deprecated. So it pointed me to ClassTag. Googled that and found this resource which I'm trying to follow: https://docs.scala-lang.org/overviews/reflection/typetags-manifests.html#via-the-methods-typetag-classtag-or-weaktypetag
So I tried doing below:
private def doSomeStringProcessing[T: TypeTag](input: String, typeConverter: String => T): Array[T] = {
cleanTheString(input)
.split(",").map(typeConverter)
}
Which gives the exact same error. I want generics to make my code cleaner/easier to read, not convoluted, so I don't want to do any of the complicated solutions. What's the quickest way to fix this?
Upvotes: 0
Views: 297
Reputation: 1845
This does work with ClassTag (I got confused because IntelliJ imported and/or code-completed it wrong, so including the correct import below):
import scala.reflect.ClassTag
private def doSomeStringProcessing[T: ClassTag](input: String, typeConverter: String => T): Array[T] = {
cleanTheString(input)
.split(",").map(typeConverter)
}
Upvotes: 4