Reputation: 2878
I am reading the book Programming in Scala and in chapter 10 I had to write:
abstract class Element {
def contents: Array[String]
def height: Int = contents.length
def width: Int = if (height == 0) 0 else contents(0).length
}
class ArrayElement(conts: Array[String]) extends Element {
def contents: Array[String] = conts
}
but the concept I don't catch here is how can I define a method that is holding a variable? As far as I know, methods return a value, it can be a computed value or an instance variable directly, but they can't hold a value. Am I forgetting a basic concept about the programming language that applies here too?
Upvotes: 1
Views: 47
Reputation: 44967
Try this out:
abstract class Foo { def bar: Int }
class Baz(val bar: Int) extends Foo
In Scala, you can implement methods by creating member variables with same name and same type. The compiler then adds a corresponding getter-method automatically.
The member variable and the getter-method are still two different things, but you don't see much difference syntactically: when you try to access it, its both just foo.bar
, regardless of whether bar
is a method or a member variable.
In your case
def contents: Array[String] = conts
is just an ordinary method that returns an array, an equivalent way to write the same thing would be
def contents: Array[String] = {
return conts
}
Since the array is mutable, you can in principle use this method to modify entries of your array, but the method itself is really just a normal method, it doesn't "hold" anything, it just returns reference to your array.
Edit: I've just noticed that conts
is actually not a member variable. However, its still captured in the definition of the contents
method by the closure-mechanism.
Upvotes: 4