Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Everything's an object in Scala

Tags:

scala

I am new to Scala and heard a lot that everything is an object in Scala. What I don't get is what's the advantage of "everything's an object"? What are things that I cannot do if everything is not an object? Examples are welcome. Thanks

like image 482
pt2121 Avatar asked Mar 27 '13 21:03

pt2121


1 Answers

The advantage of having "everything" be an object is that you have far fewer cases where abstraction breaks.

For example, methods are not objects in Java. So if I have two strings, I can

String s1 = "one";
String s2 = "two";
static String caps(String s) { return s.toUpperCase(); }
caps(s1);  // Works
caps(s2);  // Also works

So we have abstracted away string identity in our operation of making something upper case. But what if we want to abstract away the identity of the operation--that is, we do something to a String that gives back another String but we want to abstract away what the details are? Now we're stuck, because methods aren't objects in Java.

In Scala, methods can be converted to functions, which are objects. For instance:

def stringop(s: String, f: String => String) = if (s.length > 0) f(s) else s
stringop(s1, _.toUpperCase)
stringop(s2, _.toLowerCase)

Now we have abstracted the idea of performing some string transformation on nonempty strings.

And we can make lists of the operations and such and pass them around, if that's what we need to do.

There are other less essential cases (object vs. class, primitive vs. not, value classes, etc.), but the big one is collapsing the distinction between method and object so that passing around and abstracting over functionality is just as easy as passing around and abstracting over data.

like image 123
Rex Kerr Avatar answered Oct 14 '22 15:10

Rex Kerr