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>
.
我不明白為什么,例如在Java中聲明為返回byte []的java.security.MessageDigest.digest()方法返回Kotlin中的ByteArray,盡管Kotlin通常似乎將byte []稱為Array
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
類型不匹配:推斷類型是ByteArray?但是數組
27
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.
由於Java的限制,Kotlin有9種數組類型:Array <...>用於引用數組(在JVM意義上)和8種專用數組類型,即IntArray,ByteArray等。
https://kotlinlang.org/docs/reference/java-interop.html#java-arrays
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.
這種區別的主要原因是性能:如果我們沒有專門化數組,它會導致大量的裝箱/拆箱並使陣列變慢。這是不可接受的,因為人們可能希望更喜歡數組而不是集合的唯一原因是性能。
6
Said in short, just for future reference.
簡而言之,僅供將來參考。
ByteArray equals byte[] in Java
Array<Byte> equals Byte[] in JavaByteArray等於Java Array
中的byte []等於Java中的Byte []
No benefit from using one over the other in Kotlin, only if the code is to be parsed to Java.
只有在將代碼解析為Java時,才能在Kotlin中使用其中一個。
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/02/26/7203d7f9235b45744350eba92ae64e5a.html。