2D Array without copy

val arr: Array[Array[Int]] = ...

I’d like to produce a value of type IArray[IArray[Int]] without any array copying.

This is clean but involves a copy:

IArray.unsafeFromArray(arr.map(IArray.unsafeFromArray))

This involves no copy but is not particularly clean:

arr.asInstanceOf[IArray[IArray[Int]]]

Is this hopeless from lack of a 2D variant of unsafeFromArray in the library?

AFAIK all unsafeFromArray does is call asInstanceOf, and while I do like those aliases to avoid calling the cats myself, if you know what you are doing, then just cast.
If you please, make your own function to preserve some kind of typesafety.

This is the definition of unsafeFromArray:

def unsafeFromArray[T](s: Array[T]): IArray[T] = s

It doesn’t even need asInstanceOf, a reason why why I’d prefer the converting function to be in the library instead of in my code.

Oh, right, it can do that because it is an opaque and it is in the visible scope. But, again, doing asInstanceOf is fine.
I do get your point about it being better in the object itself, but making changes to the stdlib requires some effort, and this opens the door to how many nested levels it should support? Only 2, 3, 5, 10?

Thinking about it, since in essence, no matter the level of nesting, this can be just an asInstanceOf. I wonder if a match type can be used to support arbitrary nesting; if so, that addition to the stdlib would be more welcome IMHO.

No, because that would require matching on an open type hierarchy, which you must never do with a match type.

1 Like

Maybe adding mapConserve to Array would be enough?

The implementation would have to guarantee that it would only allocate a new array on a mismatch (and not upfront)… Although that’s still slower than just casting.