Home > Enterprise >  Converting java to kotlin -- streams
Converting java to kotlin -- streams

Time:07-23

I am learning Kotlin, and not know it properly. I have a piece of code in Java:

  private static Signature[] createSignatures(String... encodedSignatures) {
    return Arrays.stream(encodedSignatures)
        .map(encodedSignature -> new Signature(Base64.decode(encodedSignature, Base64.DEFAULT)))
        .toArray(Signature[]::new);
  }

I want to convert it to Kotlin, and I have reached till here:

private static Signature[] createSignatures(String... encodedSignatures) {
    return Arrays.stream(encodedSignatures)
        .map(encodedSignature -> new Signature(Base64.decode(encodedSignature, Base64.DEFAULT)))
        .toArray(Signature[]::new);
  }

But the above doesn't work, especially the line at the end, that is, .toArray(Signature[]::new) is the problem. How do I solve it? What is the correct way to convert streams to array in kotlin?

CodePudding user response:

You can achieve your goal by using following code:

private fun createSignatures(vararg encodedSignatures: String): Array<Signature> {
    return encodedSignatures
        .map { Signature(Base64.decode(it, Base64.DEFAULT)) }
        .toTypedArray()
}

CodePudding user response:

Try this:

private fun createSignatures(vararg encodedSignatures: String): Array<Signature?>? {
    return Arrays.stream(encodedSignatures)
        .map { encodedSignature -> Signature(Base64.decode(encodedSignature, Base64.DEFAULT)) }
        .toArray { _Dummy_.__Array__() }
}
  • Related