Another tour of Scala

 
 
 
 

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:String means “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 in name having 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 + "," + last is perfectly valid.
  • Type parameters are found inside square braces. Array[String] is an array of type string (the same as List<String> in Java)
  • declaring something as a val means it cannot be changed; val age = 30 is identical to the Java construct final int age = 30;
  • declaring something as a var means 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 to person toString()
  • Parens are optional for zero argument calls. person toString is identical to the two expressions above

Last Updated 07/23/2009 at 08:23:47 PM by davec

blog comments powered by Disqus