https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
t

Tobi

04/10/2019, 7:30 AM
Hello folks, I am currently working on a multiplatform library, targeting jvm and native, involving some hashing. For that I need a
ByteArray
representation of a
String
, but just realised that
String.toByteArray()
(https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/to-byte-array.html) is just available on the jvm 😞 Any suggestion how I can do this in the common part?
a

addamsson

04/10/2019, 7:40 AM
Copy code
expect fun String.toByteArray(): ByteArray
t

Tobi

04/10/2019, 7:41 AM
Thanks @addamsson, but how would you implement this using kotlin/native?
a

addamsson

04/10/2019, 7:42 AM
I'd suggest a different name though so that you can delegate to
toByteArray
on the JVM
I use
TODO()
for native 😄
t

Tobi

04/10/2019, 7:44 AM
lol
okay, maybe a question for #kotlin-native then?
a

addamsson

04/10/2019, 7:45 AM
on a more serious note i'd take a look at the jvm implementation
Copy code
/**
 * Encodes the contents of this string using the specified character set and returns the resulting byte array.
 * @sample samples.text.Strings.stringToByteArray
 */
@kotlin.internal.InlineOnly
public inline fun String.toByteArray(charset: Charset = Charsets.UTF_8): ByteArray = (this as java.lang.String).getBytes(charset)
Copy code
public byte[] getBytes(Charset charset) {
        if (charset == null) throw new NullPointerException();
        return StringCoding.encode(charset, value, 0, value.length);
    }
i'm not sure about the licensing though
you can't copy it verbatim probably
t

Tobi

04/10/2019, 7:46 AM
yep, already had a look at that.
and was hoping for another answer ^^
a

addamsson

04/10/2019, 7:47 AM
I think you can argue that if you remove the java specific parts like the system calls for security
you're good to go
😞
welcome to the fertile grounds of Kotlin common
you just have to bring your own seeds 😄
t

Tobi

04/10/2019, 7:47 AM
😆
gonna post this in #kotlin-native , maybe someone over there has a better idea
a

addamsson

04/10/2019, 7:57 AM
good idea
can you tag me there as well?
i'll have to do #kotlin-native targets at some point
t

Tobi

04/10/2019, 8:00 AM
Sure 👍
2 Views