bug icon indicating copy to clipboard operation
bug copied to clipboard

Bad type inference for java stream's `toArray`

Open He-Pin opened this issue 3 months ago • 1 comments

Reproduction steps

  • works in Scala 3.3.6
  • bad in Scala 2.13.16
  private val CLASS_STACK_WALKER: java.util.function.Function[
    java.util.stream.Stream[StackWalker.StackFrame], Array[Class[_]]] =
    (frames: java.util.stream.Stream[StackWalker.StackFrame]) =>
      frames.map(frame => frame.getDeclaringClass)
        .toArray((size: Int) => new Array[Class[_]](size))

Problem

type mismatch;
[error]  found   : Array[Class[_]]
[error]  required: Array[Class[Nothing]]
[error] Note: Class[_] >: Class[Nothing], but class Array is invariant in type T.
[error] You may wish to investigate a wildcard type such as `_ >: Class[Nothing]`. (SLS 3.2.10)
[error]         .toArray((size: Int) => new Array[Class[_]](size))

How to fix:

Add the [Class[_]]

  private val CLASS_STACK_WALKER: java.util.function.Function[
    java.util.stream.Stream[StackWalker.StackFrame], Array[Class[_]]] =
    (frames: java.util.stream.Stream[StackWalker.StackFrame]) =>
      frames.map(frame => frame.getDeclaringClass)
        .toArray[Class[_]]((size: Int) => new Array[Class[_]](size))

https://github.com/apache/pekko/pull/2260

He-Pin avatar Sep 22 '25 05:09 He-Pin

Possible umbrella ticket https://github.com/scala/bug/issues/11248

som-snytt avatar Sep 22 '25 05:09 som-snytt