Can't make simple Streams over indirect projects work
Brian Goetz
brian.goetz at oracle.com
Sun Jul 28 13:22:48 UTC 2019
This is not related to your streams issue, but don’t use __WithField, write a regular ctor. WF is there for testing and will go away.
Try rewriting your stream with all explicit types, including generic withesses,
To rule out type inference issues.
Sent from my MacBook Wheel
> On Jul 28, 2019, at 9:14 AM, Ben Evans <benjamin.john.evans at gmail.com> wrote:
>
> Hi,
>
> I'm probably missing something really obvious, but I've been playing
> with this code for several days and can't find my bug.
>
> Given an inline class defined like this:
>
> public inline class OptionalInt {
> private static final OptionalInt EMPTY = OptionalInt.default;
>
> private boolean isPresent = false;
> private int v = 0;
>
> public static OptionalInt empty() {
> return EMPTY;
> }
>
> public static OptionalInt of(int val) {
> OptionalInt self = OptionalInt.default;
> self = __WithField(self.v, val);
> self = __WithField(self.isPresent, true);
> return self;
> }
>
> public int getAsInt() {
> if (!isPresent)
> throw new NoSuchElementException("No value present");
>
> return v;
> }
>
> public boolean isPresent() {
> return isPresent;
> }
>
> public void ifPresent(IntConsumer consumer) {
> if (isPresent)
> consumer.accept(v);
> }
>
> public int orElse(int other) {
> return isPresent ? v : other;
> }
> }
>
> and some code that attempts to use it like this:
>
> public final class Main4 {
> public static void main(String[] args) {
> List<OptionalInt?> opts = new ArrayList<>();
> for (int i=0; i < 5; i++) {
> opts.add(OptionalInt.of(i));
> opts.add(OptionalInt.empty());
> opts.add(null);
> }
>
> Integer total = opts.stream()
> .map((OptionalInt? o) -> {
> if (o == null)
> return 0;
>
> OptionalInt op = (OptionalInt)o;
> return op.orElse(0);
> })
> .reduce(0, (x, y) -> x + y);
>
> System.out.println("Total: "+ total);
> }
> }
>
> Then javac barfs like this:
>
> bevans$ javac -XDallowWithFieldOperator -XDallowGenericsOverValues
> javamag/Main4.java
>
> javamag/Main4.java:15: error: ')' expected
> .map((OptionalInt? o) -> {
> ^
> javamag/Main4.java:15: error: : expected
> .map((OptionalInt? o) -> {
> ^
> javamag/Main4.java:15: error: ';' expected
> .map((OptionalInt? o) -> {
> ^
> javamag/Main4.java:20: error: illegal start of expression\
> })
> ^
> 4 errors
>
> Could some kind person put me out of my misery and tell me what I'm
> doing wrong here, and what the proper way to express this should be?
>
> Thanks,
>
> Ben
More information about the valhalla-dev
mailing list