I am trying to create a class that takes in a function, however, I want this to be optional and if the caller leaves it out, I want it to be substituted with a default function.
Currently I have the following:
class MenuItem(val text: String, val onClick: (Vector2f) => Unit) extends Renderable {
def this(text: String) = this(text, { position => () })
private def default(position: Vector2f) = {
println(text + " was clicked, but is still using the default event.")
}
}
This works fine but I want to replace the { position => () }) in the constructor with default but doing this results in the error ‘not found: value default’.
I’ve tried declaring default without the private modifier but this didn’t help.
The best solution I came up with was to declare it like this:
def this(text: String) = this(text, position => println(text + " was clicked, but is still using the default event."))
Is there a way I can leave the default method defined and just use its name or will I have to stick to implementing the method inline?
This should work (removed the weird types to make it compilable):
Accessing a method of the object you are trying to construct doesn’t work because it is only accessible once it is constructed.
From the Language Specification Section 5.3.1:
The ‘self constructor invocation is the call to the primary constructor. And since it is type checked in the scope of the enclosing class means it does not see the methods inside the class.
This is a good thing, because before the primary constructor is called, the fields of the instance (
textin this case) aren’t defined.