[英]Scala Array map returns ArraySeq
Why can't I have type parameters in my factory methods below? 为什么我的工厂方法下面没有类型参数?
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.FunSuite
@RunWith(classOf[JUnitRunner])
class WhyScalaNeverWillMakeIt extends FunSuite {
test("Array becomes ArraySeq when you least want it") {
val arr = Array("A", "B", "C")
def f: String => Dummy = new Dummy(_)
val bucket = new Bucket[Dummy](arr.map(f))
// val bucket2 = Bucket[String, Dummy](arr, f)
// val bucket3 = Bucket[Dummy](arr, f)
val bucket4 = Bucket(arr, f)
}
class Bucket[T]( val arr: Array[T] ) {/* Loads of business logic */}
object Bucket {
// def apply[T, U](arr: Array[T], f:T=>U):Bucket[U] = new Bucket[U](arr.map( b => f(b) ))
// def apply[T](arr: Array[String], f:String=>T):Bucket[T] = new Bucket[T](arr.map( b => f(b) ))
def apply(arr: Array[String], f:String=>Dummy):Bucket[Dummy] = new Bucket[Dummy](arr.map(f))
}
class Dummy(val name: String)
}
If I uncomment the factory methods in object Bucket
I get: 如果我取消注释
object Bucket
的工厂方法,我得到:
error: type mismatch;
found : scala.collection.mutable.ArraySeq[T]
required: Array[T]
def apply[T](arr: Array[String], f:String=>T):Bucket[T] = new Bucket[T](arr.map( b => f(b) ))
Somehow the Scala compiler got confused (or is it me? ;-) ) when I introduced the type parameter T. Maybe I'm doing something very wrong here, but I can't see why introducing a type parameter means that the map function should change return type from Array[T] to ArraySeq[T]. 当我介绍类型参数T时,不知何故Scala编译器感到困惑(或者是我?;-))。也许我在这里做了一些非常错误的事情,但我看不出为什么引入类型参数意味着地图函数应该将返回类型从Array [T]更改为ArraySeq [T]。
I know that Array is just a wrapper around Java Array and that I probably should use one of the more fancy Scala classes, such as Seq or List, but that still doesn't explain this rather odd behaviour. 我知道Array只是Java Array的一个包装器,我可能应该使用一个更奇特的Scala类,比如Seq或List,但这仍然无法解释这种奇怪的行为。
Can someone explain why this is happening and maybe also how to fix it (still using Arrays)? 有人可以解释为什么会发生这种情况,也许还有解决方法(仍在使用数组)?
Edit: I'm using scala 2.9.1 编辑:我正在使用scala 2.9.1
Just add ClassManifest
context bound: 只需添加
ClassManifest
上下文绑定:
def apply[T, U: ClassManifest](arr: Array[T], f: T => U): Bucket[U] = new Bucket[U](arr.map(b => f(b)))
def apply[T: ClassManifest](arr: Array[String], f: String => T): Bucket[T] = new Bucket[T](arr.map(b => f(b)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.