2

How do I encode a String in Ceylon as UTF-8 bytes?

value string = "my_string";
[Byte*] bytes = string.______;
drhagen
  • 8,331
  • 8
  • 53
  • 82

1 Answers1

3

Use ceylon.buffer.charset.

import ceylon.buffer.charset {
    utf8
}

shared void run() {
    value string = "my_string";
    List<Byte> bytes = utf8.encode(string);
    Byte[] bytesSequence = bytes.sequence(); // in case a List isn’t enough
}

Try it!

Lucas Werkmeister
  • 2,584
  • 1
  • 17
  • 31
  • Just so I understand Ceylon best practices, why does `encode` return a `List` rather than a `Byte[]`? I thought `List` was for things that were possibly mutable. – drhagen Apr 01 '18 at 19:48
  • 1
    @drhagen no, the `List` interface doesn't say anything at all about mutability. A `List` might be mutable or immutable. OTOH, I'm not quite sure why `encode()` doesn't just return a lazy stream, i.e. `{Byte*}`. – Gavin King Apr 02 '18 at 14:08