First impression in Scala by a Java coder
As a Java coder (and also some other languages) who envies Ruby concise features, I think Scala language is worth to try. I even eager to try this new language after Twitter popularize its use.
Scala bytecodes + Scala libraries = Java bytecodes
Actually, Scala is just another language which runs above JVM. You don't have to compile your source codes if you don't need to. But it is much faster to compile them into bytecodes. This fact makes you can deploy your Scala application in any Java servers or environments as long as you bring the Scala library along. Scala is also strictly typed which means you may get compile error.
Hello World
This is Java
public class First {
public static void main(String[] args) {
String name = "Sancho"
System.out.println("Hello " + name + "!");
}
}
This is Scala
object First {
def main(args: Array[String]): Unit = {
var name = "Sancho"
println("Hello " + name + "!")
}
}
See what are the differences with Java?
- Static method is not defined in class First but in singleton object named First.
- Type is defined after the field name. Instead of "String[] args", Scala uses "args: Array[String]". This also applies to main method which uses Unit as the method's return value. Unit means void in Scala.
- No need to define type of variable. Scala will detect from it's value.
- No more ; required
Method can be passed as argument
This is totally different with Java. Scala is just like a mix of object oriented programming (OOP) language and functional programming language. See this example
object First { // 0. Fungsi yang statis menggunakan object
def main(args: Array[String]) {
loop(sayHello, 2)
loop(() => println("Suki"), 3)
}
def sayHello() {
println("Hello Jack")
}
// The first argument is a function with no parameters
def loop(callback: () => Unit, times: Int) {
1.to(times).foreach(x => callback)
}
}
See the cool things?
- Scala allows methods to be another method's arguments. You can pass sayHello.
- You can pass anonymous method
- Main method needs no type defined. As it's assumed as Unit.
- Everything in Scala is object including numbers. Int 1 has a method named "to()".
Conclusions
Cool isn't it? If you ever try Ruby, you may say Scala resembles Ruby in some aspects. But the cool things, I think it's strictly typed which helps refactoring and much faster than Ruby.
Actually there are more features of Scala to tell you. But, I think it's enough for now to impress you. May be I'll tell you more in my next post. Now, I got to do research on live connection in J2ME :D
Maybe for my next post. If you a Java coder, you'll understand some aspects.
package shape
class Rectangle(length: Double, width: Double) {
def round() = 2 * (length + width)
def area() = length * width
override def toString() = "Rectangle[length:" + length + ", width:" + width + "]"
}

Comments
Post new comment