Creating a getter of a class with a type parameter

indent preformatted text by 4 spaces

I can’t get this example to work, and I don’t know why.

class ClassExample[T](private var _value: T) {
  def value = _value
  def value_ (newValue: T): Unit = _value = newValue

class UseExample {
  val _classExample = new ClassExample(false:Boolean)

  def getCE: ClassExample[Boolean] = _classExample // here is where I get the error below

The error is "Expression of type Boolean => ClassExample[Boolean] doesn't conform to expected type ClassExample[Boolean]"

What am I doing wrong?

I’m just a scala beginner. My S/N may not be high.

• The first line in UseExample doesn’t refer to ClassExample[Boolean] rather the raw trait.

I think this is the root of the problem.

Scala has specific syntactical use of underscores. I have yet to use it myself. But it does give me the willies to see them used as elements in identifiers. I know it’s legal. The brief style guide on speaks to the issue. Me? I decided to look for other places I could mess up.

I just copy-pasted the code (into an ammonite REPL) and it runs fine.

The code you have is correct but not idiomatic. Scala knows that false is Boolean so what you have done with new ClassExample(false:Boolean) is widen the value to type Boolean, which is a no-op in this case. Just new ClassExample(false) is sufficient.

I’m having no problems pasting this into the REPL so I think the problem you are experiencing is local to your environment.

Well, technically yes – the underscore on its own is a common symbol that I generally pronounce as “whatever” – but it’s totally legal to use it as part of a symbol. I sometimes use an underscore prefix to denote private members, the same way that @Michael does with _value; there’s nothing wrong with it, although I wouldn’t say it’s a common idiom.

As for the original problem: my best guess is that the type inference isn’t doing what you expect for some reason. The error suggests that the line

val _classExample = new ClassExample(false:Boolean)

is for some reason defining _classExample as a function from Boolean to ClassExample. I’m not sure why it’s doing that (it’s not what I would expect, and I’m wondering what version of Scala you’re using), but I suspect that changing that to:

val _classExample: ClassExample[Boolean] = new ClassExample(false)

will fix it.

It’s pretty common for newer Scala programmers to rely way more heavily on type inference than experienced ones do. The type inference system is lovely and powerful, but there are lots of edge cases where it doesn’t come out with the answer you expect. In cases where you get a surprising compiler error, one of the first things to try should usually be to spell out your expected types – that will, more often than not, clarify where the problem is, and sometimes just fix it.