Path: csiph.com!eternal-september.org!feeder.eternal-september.org!reader01.eternal-september.org!.POSTED!not-for-mail From: Cecil Westerhof Newsgroups: comp.lang.java.programmer Subject: Re: getFibonacciArray() cannot call getFibonacciArray(int from) Date: Sat, 03 Aug 2019 11:11:32 +0200 Organization: Decebal Computing Lines: 61 Message-ID: <87ef22mx4r.fsf@munus.decebal.nl> References: <87o91amsyc.fsf@munus.decebal.nl> Mime-Version: 1.0 Content-Type: text/plain Injection-Info: reader02.eternal-september.org; posting-host="9028278f6a1573c2cfa07bfbf5ff71f7"; logging-data="11447"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+9gyL6GVYzkAm9iBsuWwJ+nj5RLyyCn8Y=" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/25.1 (gnu/linux) Cancel-Lock: sha1:qLz0DT55/pQVPt61z1PSsyC077Q= sha1:Un86jl/x9HxcCK25mfBx1gazfP8= Xref: csiph.com comp.lang.java.programmer:39068 Cecil Westerhof writes: > When I turn it into a class it becomes really strange. I changed the > code to: > import java.util.stream.LongStream; > import java.util.stream.Stream; > > > class Fibonacci { > long[] getFibonacciArray() { > // return getFibonacciArray(0); > return getFibonacciStreamFrom(0).toArray(); > } > > long[] getFibonacciArray(int from) { > return getFibonacciStreamFrom(from).toArray(); > } > > long[] getFibonacciArray(int from, int to) { > // check parameters > int count = to - from; > return getFibonacciStreamFrom(from).limit(count).toArray(); > } > > // Needs at least Java 9 because we use a predicate in the iterator > // Index 0 of stream i element always contains fibonacci(i) and > // index 1 always contains fibonacci(i + 1) > // So the map makes sure you have the fibonacci number > LongStream getFibonacciStream() { > return Stream. > iterate(new long[]{0, 1}, t -> t[0] >= 0, t -> new long[]{t[1], t[0] + t[1]}) > .mapToLong(t -> t[0]); > } > > LongStream getFibonacciStreamFrom(int from) { > // Check parameter > return getFibonacciStream().skip(from).map(l -> l); > } > } > > When compiling this, I get: > Fibonacci.java:26: error: method iterate in interface Stream cannot be applied to given types; > return Stream. > ^ > required: T#1,UnaryOperator > found: long[],(t)->t[0] >= 0,(t)->new l[...]t[1]} > reason: cannot infer type-variable(s) T#1 > (actual and formal argument lists differ in length) > where T#1,T#2 are type-variables: > T#1 extends Object declared in method iterate(T#1,UnaryOperator) > T#2 extends Object declared in interface Stream > 1 error This was because jshell was using Java 9, and the compiler Java 8. This is Java 9 functionality, but the error message was not clear. I have both updated to 11. -- Cecil Westerhof Senior Software Engineer LinkedIn: http://www.linkedin.com/in/cecilwesterhof