Friday, 17 May 2013

Class Parameters

I’m on the AboutClasses koan.  So far Scala is holding up its end of the promise of terseness.  For example:

class ClassWithVarParameter(var description: String)
// Which is equivalent to the following in Java:
//
// public class ClassWithVarParameter() {
//
// private String description;
//
// public ClassWithVarParameter(String description) {
// this.description = description;
// }
//
// public String description() {
// return description;
// }
//
// public void description(String description) {
// this.description = description;
// }
// }
and the immutable equivalent:

class ClassWithValParameter(val name: String)
// Which is equivalent to the following in Java:
//
// public class ClassWithValParameter() {
//
// private String description;
//
// public ClassWithVarParameter(String description) {
// this.description = description;
// }
//
// public String description() {
// return description;
// }
// }
and if you simply want a private field:

val aClass = new ClassWithPrivateFields("name")
// NOTE: aClass.name is not accessible
// Which is equivalent to the following in Java:
//
// public class ClassWithValParameter() {
//
// private String description;
//
// public ClassWithVarParameter(String description) {
// this.description = description;
// }
// }

So far, so impressed.

No comments:

Post a Comment