Scala Basics
Viewing old version d0b77787c9ea343375bb04e9de53466cd99d53af; View Current
Syntax
Some basics about Scala syntax that aren’t obvious (especially if you are coming from Java)
- The type of an object or value comes after the value, using a colon:
name:Stringmeans “name has the type String” - If Scala can figure out the type of something from the context, you don’t need to declare the type (this is called type inference).
val name = "Dave"results innamehaving the type String. This is statically assigned, and not dynamic is it would be in Ruby (e.g.) - You don’t need semicolons unless Scala can’t figure out where statements end
- Methods are defined via the “=” sign after the method signature, and don’t require braces if they are one-liners.
def toString = first + "," + lastis perfectly valid. - Type parameters are found inside square braces.
Array[String]is an array of type string (the same asList<String>in Java) - declaring something as a
valmeans it cannot be changed;val age = 30is identical to the Java constructfinal int age = 30; - declaring something as a
varmeans it can be changed - Operators can be overloaded (more precisely, the characters you are allowed in a method or function name are much more varied than in Java)
- The dot between an object and a method call is optional.
person.toString()is identical toperson toString() - Parens are optional for zero argument calls.
person toStringis identical to the two expressions above
Compiling/Running
scalac and scala work just like their java counterparts.
scalac SomeClass.scala SomeOtherClass.scala scala -cp . SomeClass
What happens when you run a class isn’t quite the same as Java, however.
object MainClassObject {
def main(args: Array[String]) {
println("Hello world!")
}
}
scala -cp . MainClassObject
(There are other ways to do this, but this is a way)
Read/Eval/Print
Like most scripting languages, and unlike most compiled languages, Scala has a REPL (Read/Eval/Print Loop) where you can play around
scala Welcome to Scala version 2.7.4.final (Java HotSpot(TM) Client VM, Java 1.5.0_16). Type in expressions to have them evaluated. Type :help for more information. scala> val a = List(1,4,6,87,5,3,9) a: List[Int] = List(1, 4, 6, 87, 5, 3, 9) scala> val b = 12 :: 34 :: a b: List[Int] = List(12, 34, 1, 4, 6, 87, 5, 3, 9) scala> b res0: List[Int] = List(12, 34, 1, 4, 6, 87, 5, 3, 9) scala> a.map((item) => item * item) res2: List[Int] = List(1, 16, 36, 7569, 25, 9, 81) scala>^D
Last Updated 07/24/2009 at 01:40:56 PM by davec
blog comments powered by Disqus
All Content by David Copeland is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.