1

Quick question regrading how to define a value class in scala

Here is typical example:

class Wrapper(val underlying: Int) extends AnyVal

I am getting next error:

/usr/home/User/scala2/scala_lerning/src3/val.scala:1: error: value class may not be a member of another class
class Wrapper(val underlying: Int) extends AnyVal
      ^
one error found

OS: FreeBSD 10.2 Scala code runner version 2.11.7 -- Copyright 2002-2013, LAMP/EPFL

Could anyone help with this?

Thanks

Reactormonk
  • 21,472
  • 14
  • 74
  • 123
Pavel
  • 1,519
  • 21
  • 29

1 Answers1

1

It seems you're doing

class Foo {
  class Wrapper(val underlying: Int) extends AnyVal
}

which you can't. You have to do

class Foo {
}
class Wrapper(val underlying: Int) extends AnyVal
Reactormonk
  • 21,472
  • 14
  • 74
  • 123
  • 1
    I am getting the same error when I am putting your code in a single file and trying to compile: scala file.scala. – Pavel Feb 18 '16 at 10:36
  • Here is also example from scala documentation. It also fails: trait Printable extends Any { def print(): Unit = println(this) } class Wrapper(val underlying: Int) extends AnyVal with Printable val w = new Wrapper(3) w.print() // actually requires instantiating a Wrapper instance – Pavel Feb 18 '16 at 10:41
  • 3
    That's because you're invoking `scala file.scala` instead of `scalac file.scala`. Apparently `scala` wraps everything into a toplevel class to enable scripting. – Reactormonk Feb 18 '16 at 10:43