Scala Basics
Viewing old version 89553d7bda439ce3d828da8599c2ac4fe15e10a7; View Current
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
Last Updated 07/23/2009 at 08:23:47 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.