28
votes

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

2
Current docs for Kotlin arrays: kotlinlang.org/docs/reference/basic-types.html#arrays and for interop with Java arrays from Kotlin: kotlinlang.org/docs/reference/java-interop.html#java-arraysJayson Minard

2 Answers

41
votes

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.

25
votes

Said in short, just for future reference.

ByteArray equals byte[] in Java
Array<Byte> equals Byte[] in Java

No benefit from using one over the other in Kotlin, only if the code is to be parsed to Java.