Can I limit the size of an array in Scala?
In Java 开发者_开发技巧byte[] st = new byte[4096]
, implies that size of array st
will not exceed 4096 bytes.
The Scala equivalent is st:Array[byte] = Array()
where size is unknown. If I am reading a huge file into this array, then how can I limit the size of the array?
Will there be any side effect if I don't care about the size for the above operation?
var buffer = new Array[Byte](4 * 1024)
Works just fine, and it behaves as expected.
You Java example does not produce an array with an upper bound on its size, it produces an array with precisely the stated size, which is fixed throughout its lifetime. Scala arrays are identical in this regard. Additionally, this:
val st: Array[Byte] = Array()
allocates an array of Byte ("byte" in Java) of length 0.
As far as reading a file into an array, if you must process the entire file, then attempt to allocate the required space and if it fails, you can't proceed.
In case your are late to the Party:
val buffer = new Array.ofDim[Byte](4 * 1024)
精彩评论