Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between ByteArray and Array<Byte> in kotlin

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

like image 506
lathspell42 Avatar asked Feb 26 '12 22:02

lathspell42


People also ask

What is Bytearray in Kotlin?

Creates a new array of the specified size, where each element is calculated by calling the specified init function.

What is the difference between ByteBuffer and byte array?

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.

Is byte array same as string?

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.

What is Bytearray?

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.


1 Answers

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.

like image 145
Andrey Breslav Avatar answered Sep 18 '22 19:09

Andrey Breslav