比方说,我有这样的功能(这只是一个例子,所以不要给我更好的方法来创建0,1,2,...风格数组):斯卡拉:奇怪的类型不匹配错误
def createArray(size: Int): Array[Int] = {
for (i <- 0 until size) yield i
}
但是,编译生气与一些神秘的类型不匹配错误:
(fragment of compare-images.scala):39: error: type mismatch;
found : RandomAccessSeq.Projection[Int]
required: Array[Int]
for (i <- 0 until size) yield i
^
one error found
!!!
discarding <script preamble>
我敢肯定,原因有事可做的事实,until
方法的返回类型为Range
,不Array
。然而,为什么编译器不能只投射这些类型呢? 有趣的问题消失了,当我删除我的函数的返回类型:
def createArray(size: Int) = {
for (i <- 0 until size) yield i
}
但我想我的函数返回Array
...
我也有另一种功能,它是这样的:
def screateArray2: Array[Int] = {
val a = Array(1,2,3,4,5)
for (i <- a) yield i
}
它编译没有任何问题。它产生的值非常类似于第一个例子,但直到方法才使用...
我是否错过了有关Scala的类型系统?
我对Scala很陌生。
编辑:我有点解决我的问题是这样的:
def crop(data: Array[Int]): Array[Int] = (
for (i <- 0 until data.size) yield i
).toArray
但在我看来,这是什么,但可读......
我应该说之前你不需要值“推断“(或者Scala编译器用来匹配类型)而不是”cast“。 – 2010-07-25 09:08:10
但是类型不匹配,因为Range不是Array的子类型,所以在这里没有推断正确结果类型的问题。你必须做一个转换来获得。 – 2010-07-25 09:40:59
是的,但你真的不必是一个天才编译器来自动将Range转换为Array,而不是打扰类型不匹配错误:) – 2010-07-25 18:32:27