简体   繁体   中英

How to run a scala value class in a jupyter notebook

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

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!

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM