Let's say I have a function like this (it's only an example, so do not offer me better ways to create 0,1,2,... style array):
def createArray(size: Int): Array[Int] = {
for (i <- 0 until size) yield i
}
But the compiler get upset with some mysterious type mismatch error:
(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>
I'm sure, the reason has something to do with the fact that until
method's return type is Range
, not Array
. Yet, why the compiler can't just cast the types?
Interestingly the problem goes away when I remove the return type of my function:
def createArray(size: Int) = {
for (i <- 0 until size) yield i
}
But I want my function to return Array
...
I also have another function, which goes like this:
def screateArray2: Array[Int] = {
val a = Array(1,2,3,4,5)
for (i <- a) yield i
}
It compiles without any problems. It yields values very similarly to the first example, but doesn't use until method...
Am I missing something about Scala's type system?
I'm quite new to Scala.
EDIT: I sort of solved my problem like this:
def crop(data: Array[Int]): Array[Int] = (
for (i <- 0 until data.size) yield i
).toArray
But in my view it's anything but readable...