A suggestion to improve Text Blocks

Brian Goetz brian.goetz at oracle.com
Fri Jan 17 02:50:01 UTC 2020


This behavior is already available through the lines() method on 
String.  You can do:

     String items = """
         Apple
         Orange
         Banana""";

     List<String> itemList = items.lines().collect(toList());
or
     String[] itemArray = items.lines().toArray(String[]::new);

Given that the functionality is readily available in an ordinary library 
method, introducing magic ad-hoc conversions in the language (which has 
probably 100-1000x the cost of a library method) seems ill-advised; they 
add lots of complexity and irregularity for little benefit.  (Magic 
conversions are not easily discoverable; they don't always cover the set 
of conversions you want and can't be extended, which often leads to 
complaints of "please also support conversion to <my favorite 
collection>; etc.)  Further, a magic way of slicing text blocks wouldn't 
apply to strings produced in other ways; on the other hand, an ordinary, 
well-specified method like String::lines can work on any string, 
regardless of its provenance.

I think what you really want, and are trying to get there indirectly, is 
_collection literals_.  Which is a useful, and far^3 more generally 
applicable feature, which we might be able to justify some day.  In the 
meantime, you can use general-purpose methods like List::of in its place:

     List<String> fruits = List.of("Apple",
                                   "Orange",
                                   "Banama");

which is only a few more characters than your example, but with less magic.



On 1/16/2020 6:26 PM, P Holder wrote:
> I would like to see the compiler be able to do a little more work
> while compiling Text Blocks, and to be able to handle these cases
> intelligently by treating each line (where it would have emitted a
> newline) as a separate element.
>
> String[] itemsInArray = """
>    Apple
>    Orange
>    Banana
>    Kiwi
>    """;
> which would result in itemsInArray [4], where itemsInArray[0] =
> "Apple" and itemsInArray[3] = "Kiwi"
>
> List<String> itemsInArray = """
>    Apple
>    Orange
>    Banana
>    Kiwi
>    """;
> which would result in an unmodifiable List<String> with entries like
> "Apple", "Orange", etc.



More information about the amber-dev mailing list