Scala compiling a value class is not suitable for a base type with a partial function method

Let's say I defined a class of values ​​as follows

package object p {
  class ValueClass[T](val o: Option[T]) extends AnyVal {
    def foo: Option[T] =
      o collect {
        case t => t
      }
  }
}

Compilation error with message:

overriding method applyOrElse in trait PartialFunction of type [A1 <: T, B1 >: T](x: A1, default: A1 => B1)B1;
  method applyOrElse has incompatible type
       o collect {
                 ^

The error message does not seem to me as significant as if I replaced it collectwith map(which requires a function instead of a partial function) or the class does not extend AnyVal, the code fragment will compile.

Can someone explain the reason or link to the problem presented?

+4
source share
1 answer

This one good. It works in 2.11.0-M8, at least.

Obviously

https://issues.scala-lang.org/browse/SI-8011

exact match

https://issues.scala-lang.org/browse/SI-8018

2.10.x,

scala> trait X[A] { def pf: PartialFunction[A,A] = { case a => a } }
defined trait X

scala> class X[A](val x: A) extends AnyVal { def pf: PartialFunction[A,A] = { case a => a } }
<console>:7: error: overriding method applyOrElse in trait PartialFunction of type [A1 <: A, B1 >: A](x: A1, default: A1 => B1)B1;
 method applyOrElse has incompatible type
       class X[A](val x: A) extends AnyVal { def pf: PartialFunction[A,A] = { case a => a } }
                                                                            ^

, , 2.10.3 .

:

https://issues.scala-lang.org/browse/SI-6482

https://issues.scala-lang.org/browse/SI-7022 ()

https://issues.scala-lang.org/browse/SI-6187

, , . , :

commit ff9f60f420c090b6716c927ab0359b082f2299de
Author: Paul Phillips <paulp@improving.org>
Date:   Sat Oct 6 10:20:45 2012 -0700

    Fix for SI-6482, lost bounds in extension methods.

    That was a good one. How to create a new method with type
    parameters from multiple sources, herein.

, , 2.11.0-M8 - :

apm@mara:~/goof$ scalam
Welcome to Scala version 2.11.0-M8 (OpenJDK 64-Bit Server VM, Java 1.7.0_25).
Type in expressions to have them evaluated.
Type :help for more information.

scala> class X[A](val x: A) extends AnyVal { def pf: PartialFunction[A,A] = { case a => a } }
defined class X

scala> :pa -raw
// Entering paste mode (ctrl-D to finish)

package object p {
  class ValueClass[T](val o: Option[T]) extends AnyVal {
    def foo: Option[T] =
      o collect {
        case t => t
      }
  }
}

// Exiting paste mode, now interpreting.


scala> new p.ValueClass(Some(7)).foo
res0: Option[Int] = Some(7)
+5

Source: https://habr.com/ru/post/1525686/


All Articles