Search code examples
javaarraysjava-streamcovariance

How to instantiate a Stream of String arrays by concatenating a single array with a Stream


Given a method with signature:

private String[] emitRecord(SomeType someType {...}

I would like to take theRecordAsStream defined as a stream of array of strings.

String[] someRecord = emitRecord(someType);
Stream<String[]> theRecordAsStream = Stream.of(someRecord);

and prepend it to and existing stream of arrays of string.

return Stream.concat(theRecordAsStream, eventsStream);

Unfortunately this is not possible as Stream.of(someRecord) returns a Stream which then triggers the following error on the concat.

Error:(118, 65) java: incompatible types: inference variable R has incompatible bounds
equality constraints: java.lang.String[]
lower bounds: T,java.lang.String[],java.lang.String,T

What's the proper way to deal with this?


Solution

  • You explicitly tell Stream.of(T t) that you want a Stream<String[]>, i.e. you tell it that T is a String[]:

    Stream<String[]> theRecordAsStream = Stream.<String[]>of(someRecord);
    

    That way, the compiler cannot misinterpret it as call to Stream.of(T... values), with T being a String, which is what you're currently experiencing.