I’m working to learn Scala–coming from a C++ background. I am trying
to write a small class for a task tracking app I’m hacking together to
help me to learn how to code Scala.
This seems as if it should be simple but for some reason it’s eluding me:
package com.catenacci.tts
class Task(val ID:Int, val Description:String) {
val EmptyID = 0
val EmptyDescription = "No Description"
def this() = this(EmptyID,EmptyDescription)
def this(ID:Int)={
this(ID,EmptyDescription)
}
def this(Description:String)={
this(EmptyID,Description)
}
}
I’m trying to provide three constructors: Task(ID, Description),
Task(ID), Task(Description). In the latter 2 cases I want to
initialize the values to constant values if one of the values isn’t
provided by the caller. And I want to be able to check this outside
of the class for unit testing purposes. So I figured putting in two
public vals would allow me to check from outside of the class to make
sure that my state is what I expect.
However, for some reason this code will not compile. I get the following error:
error: not found: value EmptyID
and
error: not found: value EmptyDescription
So what am I missing? I’m working through “Programming in Scala” so
if there’s a simple answer to this question, please give me page
numbers. I don’t mind reading but going by the code on page 60 and
page 62, I can’t see why this code is failing.
I’m guessing it has something to do with the fact that these are
constructor methods and that possibly the two vals are not initialized
until the end of the constructors. If that’s the case is there some
way to get the effect I’m looking for?
You can define the constants in a companion object:
And then reference them as Task.EmptyID and Task.EmptyDescription.
I think Scala 2.8 has support for default values.