Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - are classes sufficient?

Tags:

class

scala

Coming from Java I am confused by the class/object distinction of scala. Note that I do not ask for the formal difference; there are enough references on the web which explain this, and there are related questions on SO.

My questions are:

  1. Why did the designers of scala choosed to make things more complicated (compared to Java or C#)? What disadvantages do I have to expect if I ignore this distinction and declare only classes?

Thanks.

like image 432
John Avatar asked Jun 27 '10 17:06

John


2 Answers

Java classes contain two completely different types of members -- instance members (such as BigDecimal.plus) and static members (such as BigDecimal.valueOf). In Scala, there are only instance members. This is actually a simplification! But it leaves a problem: where do we put methods like valueOf? That's where objects are useful.

class BigDecimal(value: String) {
   def plus(that: BigDecimal): BigDecimal = // ...
}

object BigDecimal {
   def valueOf(i: Int): BigDecimal = // ...
}

You can view this as the declaration of anonymous class and a single instantiation thereof:

class BigDecimal$object {
   def valueOf(i: Int): BigDecimal = // ...
}
lazy val BigDecimal = new BigDecimal$object

When reading Scala code, it is crucial to distinguish types from values. I've configured IntelliJ to hightlight types blue.

val ls = List.empty[Int]  // List is a value, a reference the the object List
ls: List[Int]             // List is a type, a reference to class List

Java also has another degree of complexity that was removed in Scala -- the distinction between fields and methods. Fields aren't allowed on interfaces, except if they are static and final; methods can be overriden, fields instead are hidden if redefined in a subclass. Scala does away with this complexity, and only exposes methods to the programmer.

Finally, a glib answer to your second question: If you don't declare any objects, you're program may never run, as you to define the equivalent of public static void main(String... args) {} in Scala, you need at least one object!

like image 115
retronym Avatar answered Nov 17 '22 16:11

retronym


Scala doesn't have any notion of static methods with standard classes, so in those scenarios you'll have to use objects. Interesting article here which provides a good intro:

http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-3

(scroll down to Scala’s Sort-of Statics)

like image 35
Roy Truelove Avatar answered Nov 17 '22 16:11

Roy Truelove