Java byte[] and Kotlin ByteArray question

I am trying to convert the Java method below into Kotlin one and I have dificulties doing so. Issues are commented at the end of every troubled line. Any hint or idea will do

Java code:

public static ByteArrayOutputStream convert(InputStream stream)
{
  final ByteArrayOutputStream out = new ByteArrayOutputStream(8192);
  byte buffer = new byte[8192];
  int length;
  try
  {
  while ((length = stream.read(buffer)) > 0)
  {
           out.write(buffer, 0, length);
  }
  out.flush();
  return out;
  }
  catch (Throwable t)
  {
  // behave
  }
  return null;
}


Kotlin code:

public fun toByteArrayOutputStream(stream: InputStream) : ByteArrayOutputStream {
  val out: ByteArrayOutputStream = ByteArrayOutputStream(8192)
  var buffer: Array<Byte> = Array<Byte>(8192) // init param issue
  var length: Int = 0;

  while ((length = stream.read(buffer)) > 0) { // can’t use assignments here
  out.write(buffer, 0, length) // can’t call Java-only method
  }
  out.flush()
  return out
}

AFAIK, Array<Byte> is equivalent to java's Byte[] (the boxed byte). If you want primitive byte array, use ByteArray. Also, as compiler mentioned, you can't use assign in the while condition. So, converted code may look like this:

``

public fun convert(stream: InputStream): ByteArrayOutputStream? /* nullable / {
  val out = ByteArrayOutputStream(8192) /
out is a keyword, it may be better to choose another name for var */
  val buffer = ByteArray(8192)

  try {
  while (true) {
  val length = stream.read(buffer)
  if (length <= 0)
  break
  out.write(buffer, 0, length)
  }
  out.flush()
  return out
  } catch (t: Throwable /* it’s better to catch specific exception here, or, at least, Exception, but not Throwable */) {
  // behave
  }

  return null
}

1 Like

1,3. Use ByteArray instead of Array<Byte>, see this page for details http://confluence.jetbrains.net/display/Kotlin/Java+interoperability#Javainteroperability-Invariantarrays 2. There's no need in using this low-level Java idiom with an assignment in the expression position. Use a library cal instead: http://jetbrains.github.com/kotlin/versions/snapshot/apidocs/kotlin/io/java/io/InputStream-extensions.html

2 Likes

Thank you guys, this cleared some mist in my mind concerning array types and uses.

BTW InputStream extensions are awesome. As Kotlin itself.