Scala stack modifications on Function0

Viewed 117

I just faced very strange behavior in Scala's stack modifications.

Let's see an example:

class Base extends Function0[Unit] {
  override def apply(): Unit = println("base")
}

trait Modification extends Function0[Unit] {
  abstract override def apply(): Unit = { print("modified "); super.apply() }
}

val a = new Base with Modification
a.apply()

I expect the output to be like modified base. Instead, I got modified modified modified... resulting in a StackOverflowError

What is interesting, that's happening only with Function0[Unit]. Function[String] is working fine:

class Base extends Function0[String] {
  override def apply(): String = "base"
}

trait Modification extends Function0[String] {
  abstract override def apply(): String = "modified " + super.apply()
}

val a = new Base with Modification
a.apply()

Output:

defined class Base
defined trait Modification
a: Base with Modification = <function0>
res0: String = modified base

Could somebody please explain this behavior?

1 Answers

Looks like a bug because with custom Function0 everything works as expected

trait Function0[+R] {
  def apply(): R
}

class Base extends Function0[Unit] {
  override def apply(): Unit = println("base")
}

trait Modification extends Function0[Unit] {
  abstract override def apply(): Unit = { print("modified "); super.apply() }
}

val a = new Base with Modification

a.apply() // modified base

Bugs should be reported here: https://github.com/scala/bug/issues

Related