简体   繁体   English

Scala类型与泛型ArraySeq [T]而不是Array [T]不匹配

[英]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. 通过一些谷歌搜索,发现帖子说要使用ClassManifest。 Tried that and it was deprecated. 试了一下,不推荐使用。 So it pointed me to ClassTag. 因此,它指向了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 在Google上搜索并找到了我要遵循的资源: 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): 这确实适用于ClassTag(我很困惑,因为IntelliJ导入错误和/或代码完成错误,所以在下面包括正确的导入):

import scala.reflect.ClassTag

 private def doSomeStringProcessing[T: ClassTag](input: String, typeConverter: String => T): Array[T] = {
   cleanTheString(input)
            .split(",").map(typeConverter)
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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