1

I am attempting to run the following code in a Jupyter notebook:

trait Printable extends Any {
   def print(): Unit = println(this)
}

class Wrapper(val underlying: Int) extends AnyVal with Printable

object Demo {
   def main(args: Array[String]) {
      val w = new Wrapper(3)
      w.print() // actually requires instantiating a Wrapper instance
   }
}

Demo.main(Array())

When the cell is executed an error message appears:

Name: Compile Error
Message: <console>:15: error: value class may not be a member of another class
       class Wrapper(val underlying: Int) extends AnyVal with Printable
             ^
StackTrace:

I believe this occurs because Jupyter may be running the scala command instead of the scalac command, and apparently scala wraps everything into a top-level class to enable scripting. A value class cannot be an inner class and hence the reason for the error. There was a related question on this topic:

scala: how to define a value class

Is there a possible workaround to this issue?

I am running Apache Toree Scala with my Jupyter notebook.
OS: OS X 10.11.6, Scala 2.11.8, Jupyter 4.3.0, Apache Toree 0.2.0.

Thanks in advance!

Community
  • 1
  • 1
ecampana
  • 13
  • 6

1 Answers1

1

If you modify your Wrapper class so that it no longer extends AnyVal, then it's no longer a "value class" and your problem will go away. But if you do that, you will no longer inherit the print function from AnyVal, getting it from Any instead (Any is the superclass of all classes, like Object in Java). So to retain the same functionality, you will have to override the print function:

trait Printable extends Any {
   def print(): Unit = println(this)
}

class Wrapper(val underlying: Int) extends Printable {
  override def print(): Unit = println(underlying)
}

object Demo {
   def main(args: Array[String]) {
      val w = new Wrapper(3)
      w.print() // actually requires instantiating a Wrapper instance
   }
}

Demo.main(Array())
Paul
  • 1,939
  • 1
  • 18
  • 27
  • Thank you! This solved my problem. Does scala syntax require a person to use "extends Printable" instead of "extends AnyVal with Printable"? Or is this only needed in this instance because scala is being used in a Jupyter notebook environment? – ecampana Sep 26 '17 at 02:17
  • Good to hear that. :-) I have edited my answer to try to make it clearer why this solves the problem. If you are confused about "extends" and "with", have a look here: https://stackoverflow.com/questions/41031166/scala-extends-vs-with – Paul Sep 27 '17 at 13:32