I don't understand why e.g. the java.security.MessageDigest.digest()
method which is declared as returning byte[]
in Java returns a ByteArray
in Kotlin although Kotlin usually seems to call byte[]
an Array<Byte>
.
E.g. the following does not work:
fun main(args : Array<String>) { val md = java.security.MessageDigest.getInstance("SHA") if (md == null) throw NullPointerException() val result : Array<Byte>? = md.digest() }
Type mismatch: inferred type is ByteArray?
but Array<Byte>?
was expected
Creates a new array of the specified size, where each element is calculated by calling the specified init function.
There are several differences between a byte array and ByteBuffer class in Java, but the most important of them is that bytes from byte array always reside in Java heap space, but bytes in a ByteBuffer may potentially reside outside of the Java heap in case of direct byte buffer and memory mapped files.
Since bytes is the binary data while String is character data. It is important to know the original encoding of the text from which the byte array has created. When we use a different character encoding, we do not get the original string back.
A byte array is simply a collection of bytes. The bytearray() method returns a bytearray object, which is an array of the specified bytes. The bytearray class is a mutable array of numbers ranging from 0 to 256.
Due to Java's limitations, Kotlin has 9 array types: Array<...> for arrays of references (in the JVM sense) and 8 specialized array types, i.e. IntArray, ByteArray etc.
https://kotlinlang.org/docs/reference/java-interop.html#java-arrays
The main reason for this distinction is performance: if we didn't specialize arrays it'd lead to a lot of boxing/unboxing and make arrays slow. This would be unacceptable because the only reason one might want to prefer arrays over collections is performance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With