I just stumbled over something really funny; something that would fit to the Watman lightning talk by Gary Bernhardt. As you may know, Java is jet another language that copied a really great programming language of the visionary Alan Kay, named Smalltalk. In Smalltalk everything is an Object (yes, really really everything! So even classes are objects, describes by meta-classes – even creating a subclass is done by sending the superclass a message, to which it replies with a subclass!) and all programming is done by objects sending and receiving messages, and answering to them. This is why in OOP, you don’t have functions but methods. A function can be called – it can be applied to values. So you actually define what to do. In OOP, an object decides on how to properly react on a message. It does so by looking up it’s methods on how to react on the received message. But how it will react is totally up to the object, it’s even possible that many different objects reply to the same message by using different methods; a function on the other hand is unique. But the key idea is that while in imperative programming you see and apply the function, in object-oriented programming this is a black-box to you (unless you programmed the method).
But I digress. Coming back to Java, when it was developed, it wanted to implement OOP, but on the other hand it also wanted to keep up with the speed popularity of C. So not only did the syntax change to be more C-like, but also a lot of things that work purely object-oriented in Smalltalk where implemented as they are in C. This also applies to numbers, they are primitives; values that lie in RAM, values on which functions are applied to. Now, this may sound totally normal to us – we don’t think of a number as an object, which we ask to do something, and then see if it does it, or not. But with Smalltalk, that’s exactly how it’s done:
1 class => SmallInteger 1 resondsTo: #+ => true
1.class => Fixnum 1.respond_to?(:+) => true
So how does it work?
+ is a method, same as any other method – with the exception that it is written in a special way, so that it can be used more human-readable, in an infix notation. #+ and :+ are symbols in Smalltalk/Ruby, which are used to identify the method. Say you have a method called
println(), the symbol would be
:println in Ruby or
#println in Smalltalk. Ruby allows us to send a message to a object not only by naming the method, but also by using the
send()-Method, that every object understands, and where the first argument is the the symbol of the method and the following arguments are arguments accepted by the method. So, here it should become obvious that + is actually a method and the second number (another object) an argument:
1.send(:+, 2) => 3
The Answer to the message is actually a new object. Not so in Java. Primitives are non-object values
System.out.println(1.getClass()); => Unresolved compilation problem: Cannot invoke getClass() on the primitive type int