Search code examples
kotlinappendstringbuilder

Passing StringBuilder::append as argument in Kotlin


I'm using BIP39 plugin for Java to create a mnemonic. So I've converted (well mostly IDEA did) this Java code to a function in Kotlin syntax which looks like this:

fun mnemonicBuilder(): String {
  val sb = StringBuilder()
  val entropy = ByteArray(Words.TWELVE.byteLength())
  SecureRandom().nextBytes(entropy)
  MnemonicGenerator(English.INSTANCE)
      .createMnemonic(entropy, sb::append)
  return sb.toString()
}

IntelliJ IDEA keeps telling me that "None of the following functions can be called with the arguments supplied." for sb::append.

My quess is that .createMnemonic requires the second argument to have no return value (given by Target interface) but all appenders return the StringBuilder as a value.

Please, can somebody help me?


Solution

  • Indeed, argument signatures do not match. You can solve it by using lambda instead of the method reference:

    MnemonicGenerator(English.INSTANCE)
        .createMnemonic(entropy) { sb.append(it) }