It's different because it natively inherits all of Java's classes and has interoperability without all the garbage. There are plenty of discussions about this available so it's not necessary to duplicate one here. Lets just say that inferred typed variables feels nice for a change. I thought that PHP was messy because variables did not need typed and this was one of the strict things about Java that I liked. Each day I like it less and less. Why for instance does one need to define the primitive types like String var = " "; when it is quite obvious that it is a string there in those quotes? Scala can just infer this is a string without the hand-holding var = " ".
Oh and no trailing semi-colon; that was no typo. It is not necessary when the line ending is obvious.
I'm going to go against the grain of the computer overlords and not demonstrate 'Hello, World!' application. Instead lets do something fun, that everyone loves, recursion. Well not just any recursion, Fibonacci numbers.
Java
public int fibonacci(int num) {
return num <=1 ? num : fibonacci(num-1) + fibonacci(num-2);
}
Now we're going to do a direct conversion to Scala. If you read the language ref, there is no ternary condition so we have to go with if-else. There is a really cool reason for this, however. In Scala we can use one expression and use the if-else to compare it. More on this if necessary.
Scala
def fibonacci(num: int): int= {
if (num<=1) return num
else
return fibonacci(num-1) + fibonacci(num-2)
}
Those of us with a C background may have thrown up a little bit in your throat looking at that. Relax, it's easy to follow. def defines our method, num: int says we're accepting an integer param and int= { } says we're returning an int type. Simple right? We'll move on in future discussions to web frameworks for Scala.
This is just a !HelloWorld Scala intro example. I hope this gives a brief introduction. More will follow sporadically.
1 comments:
Hey Garrett!
I'm glad you're playing with Scala. A few things I'd like to point out:
Scala's "if" -is- a ternary operator. An "if-else" expression actually returns a value. For example:
val size = if (array == null) 0 else array.size
(Of course, ideally you wouldn't use null in Scala. Prefer Option.)
Combined with methods returning their last expression (if there is no explicit "return" statement) we can say:
def fib(n: Int): Int = if (n <= 1) 1 else fib(n-1) + fib(n-2)
Of course, like the Java version, this suffers from the drawback that you can explode your stack for large values of N. (See comment on next post.)
Post a Comment