简体   繁体   中英

Scala type mismatch with generics ArraySeq[T] instead of Array[T]

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?

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)
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM