kotlin中ByteArray和Array 之间的区别

[英]Difference between ByteArray and Array 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>.

我不明白为什么,例如在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?但是数组 ?预计

2 个解决方案

#1


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.

这种区别的主要原因是性能:如果我们没有专门化数组,它会导致大量的装箱/拆箱并使阵列变慢。这是不可接受的,因为人们可能希望更喜欢数组而不是集合的唯一原因是性能。

#2


6  

Said in short, just for future reference.

简而言之,仅供将来参考。

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

ByteArray等于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中使用其中一个。

智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2012/02/26/7203d7f9235b45744350eba92ae64e5a.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告