case class Array_8to24[T](val arr:Array[T]) {
def tail():Array[T] = {
for(i <- 1 until arr.length toArray) yield arr(i)
}
}
Compiler says that tail() returns ArraySeq[T], I expected Array[T]
BTW swaps() works as expected
def swaps(arr:Array[Int]):Array[Int] = {
for(i <- 0 until arr.length toArray) yield {
if((i+1)%2 != 0 && i+1<arr.length){
arr(i + 1)
}else {
arr(if(i==arr.length-1 && arr.length%2!=0) i else i - 1)
}
}
}
How to return Array[T] from tail()?
So, the problem is that it does not know how to create an array of unknown type T
. Arrays are a special kind of containers because they are backed by native java arrays, and for that reason one needs to have the element type when the array is instantiated. Adding manifest to the declaration should fix it:
case class Array_8to24[T : Manifest](val arr:Array[T]) {
def tail(): Array[T] =
for(i <- 1 until arr.length toArray) yield arr(i)
}
You do know you could just do arr.tail
or arr.drop(1)
, right?
And swaps
could be arr.grouped(2).flatMap { case Array(a,b) => Array(b,a) case x => x }.toArray