Jan
2008
In the previous installment, we looked at the basics of Scala syntax and provided some simple conceptual explanations. Obviously there’s a lot more to this language than what I was able to present in a single (albeit very long) article. In this post we’re going to examine Scala’s object oriented constructs (classes, objects, methods, etc) and how they compare to Java.
A More Complex Example
package com.codecommit.examples import java.awt.{Color, Graphics} abstract class Shape { var fillColor:Color = null def draw(g:Graphics):Unit def area:Double } class Circle(var radius:Int) extends Shape { def draw(g:Graphics):Unit = { if (fillColor == null) { g.drawOval(0, 0, radius / 2, radius / 2) } else { g.setColor(fillColor); g.fillOval(0, 0, radius / 2, radius / 2) } } def area:Double = { var back = Math.Pi * radius back * radius } } class Square(var width:Int) extends Shape { def draw(g:Graphics):Unit = { if (fillColor == null) { g.drawRect(0, 0, width, width) } else { g.setColor(fillColor) g.fillRect(0, 0, width, width) } } def area:Double = width * width } |
Remember that Scala does not require every public class to be declared in a file of the same name. In fact, it doesn’t even require every class to be declared in a separate file. Organizationally, it makes sense for all of these trivial classes to be contained within the same file. With that in mind, we can copy/paste the entire code snippet above into a new file called “shapes.scala”.
The first thing you should notice about this snippet is the package declaration. All of these classes are declared to be within the “com.codecommit.examples” package. If this were Java, we’d have to create a new directory hierarchy to match (com/codecommit/examples/). Fortunately, Scala saves us work here as well. We can just store this file right in the root of our project and compile it in place, no hassle necessary.
With that said, it’s still best-practice to separate your packages off into their own directories. This organization makes things easier to find and eases the burden on you (the developer) in the long run. And after all, isn’t that what we’re trying to do by looking at Scala in the first place?
To compile this class, we’re going to use the fsc command (short for Fast Scala Compiler). FSC is one of those brilliant and obvious Scala innovations which allows repeated compilation of Scala files with almost no latency. FSC almost completely eliminates the compiler startup time incurred by the fact that the Scala compiler runs on the JVM. It does this by “warm starting” the compiler each time, keeping the process persistent behind the scenes. Effectively, it’s a compiler daemon, sitting in the background and using almost no resources until called upon. The command syntax is identical to the scalac command:
fsc -d bin src/com/codecommit/examples/*.scala |
This command will compile all of the .scala files within the src/com/codecommit/examples/ directory and place the resultant .class files into bin/. Experienced Java developers will know the value of this convention, especially on a larger project. Once again, Scala doesn’t intend to upset all best-practices and conventions established over decades. Rather, its purpose is to make it easier to do your job by staying out of the way.
First Impressions
Of course, compiling an example doesn’t do us much good if we don’t understand what it means. Starting from the top, we declare the package for all of the classes within the same file. Immediately following is a single statement which imports the java.awt.Color and java.awt.Graphics classes. Notice Scala’s powerful import syntax which allows for greater control over individual imports. If we wanted to import the entire java.awt package, the statement would look like this:
import java.awt._ |
In Scala, the _ character is a wildcard. In the case of an import it means precisely the same thing as the * character in Java:
import java.awt.*; |
Scala is more consistent than Java however in that the _ character also serves as a wildcard in other areas, such as type parameters and pattern matching. But I digress…
Looking further into the code sample, the first declaration is an abstract class, Shape. It’s worth noting here that the order of declarations in a file does not hold any significance. Thus, Shape could just as easily have been declared below Circle and Rectangle without changing the meaning of the code. This stands in sharp contrast to Ruby’s syntax, which can lead to odd scenarios such as errors due to classes referencing other classes which haven’t been declared yet. Order is also insignificant for method declarations. As in Java, a method can call to another method even if it is declared above the delegate.
class Person { def name() = firstName() + ' ' + lastName() def firstName() = "Daniel" def lastName() = "Spiewak" } |
Properties
Returning to our primary example, the first thing we see when we look at class Shape is the color variable. This is a public variable (remember, Scala elements are public by default) of type Color with a default value of null. Now if you’re a Java developer with any experience at all, warning sirens are probably clanging like mad at the sight of a public variable. In Java (as in other object-oriented languages), best practice says to make all fields private and provide accessors and mutators. This is to promote encapsulation, a concept critical to object oriented design.
Scala supports such encapsulation as well, but its syntax is considerably less verbose than Java’s. Effectively, all public variables become instance properties. You can imagine it as if there were mutator and accessor methods being auto-generated for the variable. It’s as if these two Java snippets were equivalent (the analog is not precise, it just gives the rough idea):
public class Person { public String name; } |
public class Person { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } |
It’s not quite like that, but you get the point of the example. What’s really happening is we’re taking advantage of the fact that in Scala, variables are actually functions. It’s a bit of an odd concept to wrap your head around coming from an imperative background, so it’s probably easier just to keep thinking of variables as variables.
Let’s imagine that we’ve got our Shape class and its public variable fillColor. Down the road we decide that we need to add a check to the mutator to ensure that the color is never red (why, I’m really not sure, but we do). In Java, this would be impossible because the variable is public and forcing the use of a mutator would change the public class signature. Thankfully, Scala allows us to easily rewrite that portion of the class without affecting the class signature or any code which actually uses the class:
abstract class Shape { private var theFillColor:Color = null def fillColor = theFillColor def fillColor_=(fillColor:Color) = { if (!fillColor.equals(Color.RED)) { theFillColor = fillColor } else { throw new IllegalArgumentException("Color cannot be red") } } } var shape = ... shape.fillColor = Color.BLUE var color = shape.fillColor shape.fillColor = Color.RED // throws IllegalArgumentException |
As you can see, the _= method suffix is a bit of magic syntax which allows us to redefine the assignment operator (effectively) for a variable. Notice from the perspective of the code using Shape, it still looks like a public field. The code snippet using Shape will work with both the previous and the modified versions of the class. Think of it, no more get* and set*… Now you can use public fields with impunity and without fear of design reprisal down the road.
Just to ensure this point is really clear, here’s the analog of the syntax in Ruby:
class Shape def initialize @fill_color = nil end def fill_color @fill_color end def fill_color=(color) raise "Color cannot be red" if color == Color::RED @fill_color = color end end |
This obvious difference being that the Scala example will be type-checked by the compiler, while the Ruby code will not. This is one of the many areas where Scala demonstrates all the flexibility of Ruby’s syntax coupled with the power and security of Java.
Abstract Methods
One of the important features of the Shape class in the example is that it’s declared to be abstract. Abstract classes are very important in object oriented design, and Scala wouldn’t be much of an object oriented language if it didn’t support them. However, looking through the definition of the class, there do not seem to be any abstract methods declared. Of course, as in Java this is perfectly legal (declaring an abstract class without abstract members), it just doesn’t seem all that useful.
Actually, there are two abstract methods in the Shape class. You’ll notice that neither the draw nor the area methods are actually defined (there is no method body). Scala detects this and implicitly makes the method abstract. This is very similar to the C++ syntax for declaring abstract methods:
class Shape { public: virtual void draw(Graphics *g2) = 0; virtual double area() const = 0; Color *fillColor; }; |
Thankfully, this is the end of Scala’s similarity to C++ in the area of abstract types. In C++, if a class inherits from an abstract base class and fails to implement all of the inherited abstract methods, the derived class implicitly becomes abstract. If such a situation occurs in Scala, a compiler error will be raised informing the developer (as in Java). The only exception to this rule are case classes, which are weird enough to begin with and will require further explanation down the road.
Constructors
Despite the best efforts of Josh Bloch, the constructor lives on in the modern object-oriented architecture. I personally can’t imagine writing a non-trivial class which lacked this virtually essential element. Now, it may not have been immediately obvious, but all of the Scala classes shown in this post have a constructor. In fact, every class (and object) has at least one constructor. Not just a compiler-generated default mind you, but an actually declared in-your-code constructor. Scala constructors are a bit different than those in Java, which are really just special methods named after the enclosing class:
public class Person { public Person(int age) { if (age > 21) { System.out.println("Over drinking age in the US"); } } public void dance() { ... } } Person p = new Person(26); // prints notice that person is overage |
In Scala, things are done a bit differently. The constructor isn’t a special method syntactically, it is the body of the class itself. The above sample is equivalent to the following bit of Scala code:
class Person(age:Int) { if (age > 21) { println("Over drinking age in the US") } def dance() = { ... } } var p = new Person(26) // prints notice that person is over-age |
Remember the first Scala example I listed in this series? (the three line HelloWorld) In this code, the body of the “main method” is implemented as a constructor in the HelloWorld object. Thusly:
object HelloWorld extends Application { println("Hello, World!") } |
The println statement isn’t contained within a main method of any sort, it’s actually part of the constructor for the HelloWorld object (more on objects in a later post). Any statement declared at the class level is considered to be part of the default constructor. The exceptions to this are method declarations, which are part of the class itself. This is to allow forward-referencing method calls:
class ChiefCallingMethod { private var i = 1 if (i < 5) { lessFive(i) } def lessFive(value:Int) = println(value + " is less than 5") } var chief = new ChiefCallingMethod() |
This code will run and successfully determine that 1 is indeed less than 5, once again proving the trustworthiness of mathematics.
This constructor syntax seems very strange to those of us accustomed to Java. If you’re like me, the first thought which comes into your head is: how do I overload constructors? Well, Scala does allow this, with a few caveats:
class Person(age:Int) { if (age > 21) { println("Over drinking age in the US") } def this() = { this(18) println("Created an 18 year old by default") } def dance() = { ... } } |
This revised Person now has two constructors, one which takes an Int and one which takes no parameters at all. The major caveat here is that all overloaded constructors must delegate to the default constructor (the one declared as part of the class name). Thus it is not possible to overload a constructor to perform entirely different operations than the default constructor. This makes sense from a design standpoint (when was the last time you declared such constructors anyway?) but it’s still a little constraining.
Constructor Properties
So you understand Scala constructors and you’re getting the feel for public instance properties, now it’s time to merge the two concepts in constructor properties. What are constructor properties? The answer has to do with a (seemingly) odd bit of Scala syntax trivia, which says that all constructor parameters become private instance vals (constants). Thus you can access constructor parameter values from within methods:
class Person(age:Int) { def isOverAge = age > 21 } |
This code compiles and runs exactly as expected. It’s important to remember that age isn’t really a variable (it’s a value) and so it cannot be reassigned anywhere in the class. However, it might make sense to change a person’s age. After all, people do (unfortunately) grow older. Supporting this is surprisingly easy:
class Person(var age:Int) { // notice the "var" modifier def isOverAge = age > 21 def grow() = { age += 1 } } |
In this code, age is no longer just a private value, it is now a public variable (just like fillColor in Shape). You can see how this can be an extremely powerful bit of syntax when dealing with simple bean classes:
class Complex(var a:Int, var b:Int) // ... val number = new Complex(1, 0) number.b = 12 |
Omission of the curly braces is valid syntax in Scala for classes which do not require a body. This is similar to how Java allows the omission of braces for single line if statements and so on. The roughly equivalent Java code would be as follows:
public class Complex { private int a, b; public Complex(int a, int b) { this.a = a; this.b = b; } public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } } // ... final Complex number = new Complex(1, 0); number.setB(12); |
Much more verbose, much less intuitive, and far less maintainable. With the Scala example, adding another property is as simple as adding a parameter to the constructor. In Java, we have to add a private field, add the getter, the setter and then finally add the extra parameter to the constructor with the corresponding code to intialize the field value. Starting to see how much code this could save you?
In our code sample way up at the top of the page, Circle declares a property, radius (which is a variable, and so subject to change by code which uses the class). Likewise Square has a property, width. These are constructor properties, and they’re about the most cruft-saving device in the entire Scala language. It’s really amazing just how useful these things are.
Conclusion
We’ve really just scratched the surface of all that Scala is able to accomplish in the object-oriented arena. The power of its constructs and the elegance of its terse syntax allows for far greater productivity, especially when dealing with a larger project. Moreover, Scala’s object oriented capabilities prove that it’s not just an interesting functional language for pasty academics but a powerful, expressive and practical language well suited to almost any real-world application.
Coming up: more on methods (including overriding) and a rundown on static members.


Comments
Great article, Daniel!
The bit about constructor parameters is a bit more complicated, though: only in case classes do they automatically become class members. Of course, even more magic is done for case classes. But with the parameters it should be something like this (unless I’m mistaken and it was even more complicated):
// n is just a constructor parameter
class A(n: Int)
// n is a public val member
class B(val n: Int)
// n is a private var member
class C(private var n: Int)
// n is a public val member
case class D(n: Int)
Another thing I’d like to mention: the possibly null fillColor is probably more familiar for people coming from Java, but in Scala, a more idiomatic way would be to use the Option type to indicate that something is optional:
abstract class Shape {
var fillColor:Option[Color] = None
…
}
class Circle(var radius:Int) extends Shape {
def draw(g:Graphics):Unit = fillColor match {
case None =>
g.drawCircle(0, 0, radius / 2, radius / 2)
case Some(color) => {
g.setColor(color);
g.fillOval(0, 0, radius / 2, radius / 2)
}
}
}
Beautiful. Thanks very much much for this series!
Nice insights, Erkki! It’s absolutely true that Option would have been the more “Scala way” to do it. Considering the benefits it carries, it’s certainly something of which one should avail oneself. The problem is as you say, null is far more familiar to those coming from Java.
I plan to cover Option in a later article (probably after pattern matching). For the moment I’m more or less transliterating Java idioms into Scala syntax and putting on some initial polish.
Not sure what you mean about constructor parameters only becoming members in case classes. This works just fine:
class TestClass(n:Int) {
def print = println(n)
}
new TestClass(2).print // prints “2″ as expected
Actually in case classes, the constructor parameters automatically become public member *vals*, whereas in regular classes the parameters are the equivalent of private member vals (though not quite, since they are parameters not values).
He means n won’t be public unless you say it is a val.
scala> class Foo(bar : Int)
defined class Foo
scala> new Foo(12).bar
:6: error: value bar is not a member of Foo
new Foo(12).bar
scala> class Foo(val bar : Int)
defined class Foo
scala> new Foo(12).bar
res31: Int = 12
Right, very true. I thought I had mentioned something about that in the article…
> What are constructor properties? The answer has to do with a
> (seemingly) odd bit of Scala syntax trivia, which says that all
> constructor parameters become private instance vals (constants).
> Thus you can access constructor parameter values from within
> methods:
If this isn’t clear I can reword it? You’re quite correct though in describing the behavior of constructor params.
Hmm… it seems you are right, I was thinking about how these give a different error message (is not a member vs. cannot be accessed):
scala> class N(a:Int) { def n = a }
scala> new N(1).n
:5: error: value n is not a member of N
scala> class M(private val a:Int) { def m = a }
scala> new M(1).m
:5: error: value m cannot be accessed in M
It’s odd actually, because both of those examples work fine for me (no errors). I am using Scala 2.6.0 (I know, I need to upgrade), could that have something to do with the different results?
Oops… there I go changing variable names *after* pasting the code into this comment box… what I meant was
new N(1).a
new M(1).a
Ah, I see what you’re saying! Yes, I’ve seen that distinction as well. It seems to be caused by the fact that Scala has three different types of fields: variables, values and parameters. All of these have different attributes, though values and parameters are practically identical.
Thanks for a great series, I’m really enjoying it
I especially like the gradual transition from Java.
A quick question though – how do you create read-only properties that are passed into the constructor, so that you can have immutable objects?
Thanks, looking forward to the rest of the series
I’ve stumbled with the same thing in the declaration of the attributes:-).
I’ve checked the Scala reference, and you always get a private attribute, the difference is if you declare class N(val a:Int) you get a “getter” for a, and if you declare class N(var a:Int), you get a “setter” and a “getter” for a, not a public attribute (didn’t tried it, but I bet you can write the setters and getters if you want, like to add some conditions ) .
@Gabriel
Yes, you can write the accessor/mutator pair yourself. Technically, you don’t really get them as methods if you’re using properties, it’s just a vanilla public field. Though, as I mentioned in the article, this technically *does* qualify as a pair of methods since that’s what all fields are, methods. The syntax for the accessor/mutator would be like this:
class Person(private var theName:String) {
def name = theName
def name_=(n:String) = theName = n
}
@James
This should do it for you:
class ImmutablePerson(val name:String, val ssn:Int)
var person = new ImmutablePerson(“Daniel”, 123456789)
person.name // works
person.name = “Joseph” // compiler error
“Of course, as in Java this is perfectly legal (declaring an abstract class without abstract members), it just doesn’t seem all that useful.”
An abstract class that has default implementations? Lucky you, not a Swing dev I guess … (i.e. AbstractAction)
This constructor syntax seems very strange to those of us accustomed to Java. => I’m (humbly) with Bloch here, it took me time to be used to statics, constructors and initialization process, it is not simple in Java …
Perhaps you could put a little comment in the head of code snippets not in Scala, with their language (syntaxes are so surface similar), like //C++. I sometimes skip text
At least with my versions of both Scala and Java : (typos)
fsc -D => fsc -d
g.drawCircle => g.drawOval
Good catch on the drawOval and -D vs -d! I’m updating the article.
Yeah, I’m planning on slightly modifying the code blocks to reflect the language more effectively. For the moment though, I’ll have to just try to keep referring to the language of which I speak in the immediately preceding sentence.
Thanks for the nice article! One thing, from the last example what I don’t understand: why is number “final” in the Java version? I was expecting “val” instead instead of “var” to mark a constant, or I am terribly wrong?
var number = new Complex(1, 0)
final Complex number = new Complex(1, 0);
@wing
Looks like a typo on my part.
I try to use val as much as possible when I write Scala. I must have just assumed I had done so when I wrote the translation into Java.
public class Complex {
private int a, b;
public Complex(int a, int b) {
this.a = a;
this.b = b;
}
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
}
// …
final Complex number = new Complex(1, 0);
number.setB(12);
I totally disagree with this. Although java is verbose(which is why I am looking at scala), but I guess if I do this is scala
class Complex(var a:Int, var b:Int)
// …
val number = new Complex(1, 0)
number.b = 12
what I am saying in java terms is Complex has two public members, a and b
so in java we have
public class Complex {
public int a;
public int b;
//I dont need a contructor
}
Complex complex = new Complex();
complex.a = 12;
//…..etc
Still more verbose…but you get my point
Unfortunately, if we use fields in Java, then we are obviating any possibility of overriding in the future. Any references to those fields are *statically* bound to the class in which they are declared. Additionally, if we want to add any value checks to the assignment semantics or perhaps change the data representation, we are sort of stuck with Java fields. This contrasts with Scala’s field semantics which are far more flexible. Specifically, Scala “fields” are really more like syntactic sugar around methods. The compiler is able to slip-stream some of this for optimization purposes, but at the language level, fields == methods. Thus, the Scala version of Complex directly corresponds with all of the flexibility of the Java version (with getters and setters). The Java version with only fields is more constrained.
I’m pretty sure Java itself doesn’t enforce putting your source in directories with the same package structure, or that classes even have to be in a Java file of the same name. I’ve had to fix code that doesn’t, not because it wouldn’t compile, but tracking the build dependencies was a lot harder.
“Experienced Java developers will know the value of this convention, especially on a larger project”
Nope, they’ll get a stomach ache and wonder why they need to know anything about wher the files are located. For years now I’ve not thought twice about where the files are located, and where the .class is generated. I don’t care…the IDE worries about that for me. By using Scala am I agreeing to take on the responsibility once again of wrangling files together, worrying about directory structures, and building my own make files as I once did with C/C++ apps and GCC?
@Taylor
No, it’s not as bad as all that. Scala builds are no more complicated than Java builds. In fact, all of the same tools work in just about the same way. Ant, Maven, Buildr (my personal favorite). None of them have any trouble with Scala’s unrestricted file conventions.
Hi,
I am new to scala.
while compiling – the compiler just hangs and java processes keeps growing. Any idea what’s going on?
C:\work\scala>scala -d bin src/com/codecommit/examples/*.scala
2009-09-24 14:19:10
Full thread dump Java HotSpot(TM) Client VM (11.3-b02 mixed mode, sharing):
“Low Memory Detector” daemon prio=6 tid=0×0225d400 nid=0×10d4 runnable [0x00000000..0x00000000]
java.lang.Thread.State: RUNNABLE
“CompilerThread0″ daemon prio=10 tid=0×0225a400 nid=0xf7c waiting on condition [0x00000000..0x0444fa10]
java.lang.Thread.State: RUNNABLE
“Attach Listener” daemon prio=10 tid=0×02259800 nid=0×8a4 runnable [0x00000000..0x00000000]
java.lang.Thread.State: RUNNABLE
“Signal Dispatcher” daemon prio=10 tid=0×0224ec00 nid=0×31c waiting on condition [0x00000000..0x00000000]
java.lang.Thread.State: RUNNABLE
“Finalizer” daemon prio=8 tid=0×02246000 nid=0×1050 in Object.wait() [0x0435f000..0x0435fa68]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
– waiting on (a java.lang.ref.ReferenceQueue$Lock)
at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:116)
– locked (a java.lang.ref.ReferenceQueue$Lock)
at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:132)
at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:159)
“Reference Handler” daemon prio=10 tid=0×02244c00 nid=0xf9c in Object.wait() [0x00ddf000..0x00ddfae8]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
– waiting on (a java.lang.ref.Reference$Lock)
at java.lang.Object.wait(Object.java:485)
at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:116)
– locked (a java.lang.ref.Reference$Lock)
“main” prio=6 tid=0×000ea000 nid=0×1234 runnable [0x0039f000..0x0039fe28]
java.lang.Thread.State: RUNNABLE
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
– locked (a java.net.SocksSocketImpl)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:519)
at java.net.Socket.connect(Socket.java:469)
at java.net.Socket.(Socket.java:366)
at java.net.Socket.(Socket.java:209)
at scala.tools.nsc.CompileSocket.getsock$1(CompileSocket.scala:210)
at scala.tools.nsc.CompileSocket.getsock$1(CompileSocket.scala:224)
at scala.tools.nsc.CompileSocket.getOrCreateSocket(CompileSocket.scala:227)
at scala.tools.nsc.CompileSocket.getOrCreateSocket(CompileSocket.scala:232)
at scala.tools.nsc.ScriptRunner$.compileWithDaemon(ScriptRunner.scala:237)
at scala.tools.nsc.ScriptRunner$.compile$1(ScriptRunner.scala:315)
at scala.tools.nsc.ScriptRunner$.withCompiledScript(ScriptRunner.scala:350)
at scala.tools.nsc.ScriptRunner$.runScript(ScriptRunner.scala:413)
at scala.tools.nsc.MainGenericRunner$.main(MainGenericRunner.scala:168)
at scala.tools.nsc.MainGenericRunner.main(MainGenericRunner.scala)
“VM Thread” prio=10 tid=0×02242c00 nid=0×17c0 runnable
What version of Scala are you using?
Scala version 2.7.5.final (Java HotSpot(TM) Client VM, Java 1.6.0_13) on windows vista
Hi Daniel,
Firstly, thanks for this series of articles, I’m working my way through them now. Very helpful.
I was trying a few things out based on the examples here and the following will not compile and I would think that it should… why am i unable to overload the function/variable defined in the ‘constructor’?
Code:
class Person(var age:Int){
def age_=(age:Int) = {
if(age > 120){
throw new IllegalArgumentException(“Too old”)
}
}
}
val person = new Person(1)
println(person.age)
person.age = 50
println(person.age)
Results in:
[ERROR]com/bob/HelloWorld.scala:18: error: ambiguous reference to overloaded definition,
both method age_= in class Person of type (Int)Unit
and method age_= in class Person of type (Int)Unit
match argument types (Int)
person.age = 50
Hello Paul,
If you want to overload teh accessors, you need to rename the property:
[code]
class Person(private var theAge:Int){
def age = theAge
def age_=(age:Int) = {
if(age > 120){
throw new IllegalArgumentException("Person.age=" + age + ": Too old")
} else {
theAge=age
}
}
}
[/code]
But with named parameters, surely renaming the constructor parameter name is changing the interface… so it’s not possible to go from e.g. class G(var named:Int) to a class with a setter without changing the externals somehow?
the class ChiefCallingMethod sample does not work. and I don’t know why…can someone guide me? im total n00b
D:\scala-2.9.0.1\scalacodes>scalac -verbose ChiefCallingMethod.scala
[search path for source files: ]
[search path for class files: C:\Program Files\Java\jdk1.6.0_23\jre\lib\resources.jar;C:\Program Files\Java\jdk1.6.0_23\
jre\lib\rt.jar;C:\Program Files\Java\jdk1.6.0_23\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.6.0_23\jre\lib\jce.jar;C:\P
rogram Files\Java\jdk1.6.0_23\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.6.0_23\jre\lib\ext\dnsns.jar;C:\Program Fi
les\Java\jdk1.6.0_23\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.6.0_23\jre\lib\ext\sunjce_provider.jar;C:\Pro
gram Files\Java\jdk1.6.0_23\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.6.0_23\jre\lib\ext\sunpkcs11.jar;D:\SCA
LA-~1.1\bin\..\lib\jline.jar;D:\SCALA-~1.1\bin\..\lib\scala-compiler.jar;D:\SCALA-~1.1\bin\..\lib\scala-dbc.jar;D:\SCALA
-~1.1\bin\..\lib\scala-library.jar;D:\SCALA-~1.1\bin\..\lib\scala-swing.jar;D:\SCALA-~1.1\bin\..\lib\scalap.jar;.]
[loaded package loader resources.jar in 593ms]
[loaded package loader java in 0ms]
[loaded package loader lang in 0ms]
[loaded package loader reflect in 0ms]
[loaded package loader annotation in 0ms]
[loaded class file D:\SCALA-~1.1\bin\..\lib\scala-library.jar(scala/package.class) in 94ms]
[loaded package loader scala in 1063ms]
[loaded class file C:\Program Files\Java\jdk1.6.0_23\jre\lib\rt.jar(java/lang/Object.class) in 0ms]
[loaded package loader io in 0ms]
[loaded package loader util in 16ms]
[loaded package loader nio in 0ms]
[loaded package loader charset in 0ms]
[loaded class file C:\Program Files\Java\jdk1.6.0_23\jre\lib\rt.jar(java/lang/String.class) in 46ms]
[loaded class file D:\SCALA-~1.1\bin\..\lib\scala-library.jar(scala/runtime/package.class) in 0ms]
[loaded package loader runtime in 0ms]
[loaded class file D:\SCALA-~1.1\bin\..\lib\scala-library.jar(scala/collection/package.class) in 0ms]
[loaded package loader collection in 16ms]
[loaded plugin continuations]
[dropping dependency on node with no phase object: msil]
[promote the dependency of explicitouter: tailcalls => specialize]
[parsing ChiefCallingMethod.scala]
ChiefCallingMethod.scala:10: error: expected class or object definition
var chief = new ChiefCallingMethod()
^
[parser in 62ms]
[total in 94ms]
one error found
D:\scala-2.9.0.1\scalacodes>
vince: The problem is probably because you are defining “var chief = new ChiefCallingMethod()” outside of a class or object. If you’re playing around with Scala, the best thing to do is use the REPL – where you can paste that code right in and it works.
If you really want to compile that code, you will need to wrap that statement in an object that extends the App trait, and then execute that.
In the code sample at the top of the page – what is the variable “back” in the “area” method for? Wouldn’t
def area:Double = Math.Pi * radius * radius
work as well?
Post a Comment