Scala Basics: Objects, Classes, Methods, Fields, and Your First Program
This tutorial introduces Scala fundamentals for Java developers, covering optional semicolons, object‑oriented concepts, identifier rules, reserved keywords, comments, whitespace handling, package definitions, import statements, and step‑by‑step examples of interactive and scripted Hello World programs.
If you were previously a Java programmer and understand Java basics, you can quickly learn Scala fundamentals.
The biggest difference between Scala and Java is that the semicolon at the end of a statement is optional.
Scala programs can be seen as collections of objects that communicate by invoking each other's methods. Below are the concepts of class, object, method, and instance variable:
Object – An object has attributes and behaviors, e.g., a dog has color and name (attributes) and can bark, run, eat (behaviors). An object is an instance of a class.
Class – A class is an abstraction of objects; an object is a concrete instance of a class.
Method – A method describes a basic behavior; a class can contain multiple methods.
Field – Each object has a unique set of instance variables (fields). Attributes are created by assigning values to fields.
First Scala Program
Interactive Programming
Interactive programming does not require creating a script file; you can use the following command:
$ scala
Welcome to Scala version 2.11.7 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_31).
Type in expressions to have them evaluated.
Type :help for more information.
scala> 1 + 1
res0: Int = 2
scala> println("Hello World!")
Hello World!Script Form
You can also create a file HelloWorld.scala and run it. The code is as follows:
object HelloWorld {
/* This is my first Scala program
* The following code will output 'Hello World!'
*/
def main(args: Array[String]) {
println("Hello, world!") // Output Hello World
}
}Compile it with the scalac command:
$ scalac HelloWorld.scala
$ ls
HelloWorld$.class HelloWorld.scala
HelloWorld.classAfter compilation, a HelloWorld.class file is generated, which can run on the Java Virtual Machine (JVM).
Run the program:
$ scala HelloWorld
Hello, world!Basic Syntax
Scala basic syntax requires attention to the following points:
Case Sensitivity – Scala is case‑sensitive; identifiers Hello and hello are different.
Class Names – The first letter of a class name must be uppercase. If a class name consists of several words, capitalize the first letter of each word (e.g., class MyFirstScalaClass).
Method Names – Method names start with a lowercase letter; if composed of several words, capitalize the first letter of each subsequent word (e.g., def myMethodName()).
Program File Name – The file name should match the object name and end with .scala. Mismatched names will cause compilation errors.
def main(args: Array[String]) – Every Scala program starts execution from the main method.
Identifiers
Scala supports two forms of identifiers: alphanumeric and symbolic.
Alphanumeric identifiers start with a letter or underscore and may contain letters, digits, or the dollar sign $. Identifiers beginning with $ are reserved for compiler‑generated names and should be avoided.
Scala follows Java‑like camelCase naming: variable and method names start with a lowercase letter, class names start with an uppercase letter, and identifiers should not end with an underscore.
Symbolic identifiers consist of one or more symbols such as +, :, ?, etc. Example:
+ ++ ::: < ? > :->When Scala is compiled, symbolic identifiers are escaped (e.g., :-> becomes $colon$minus$greater). To call such a method from Java, use the escaped name.
Mixed identifiers combine an alphanumeric part with one or more symbols, e.g., unary_+. Literal identifiers are enclosed in backticks, e.g., `x`, `yield`. To call a method whose name is a Scala keyword, use backticks: Thread.`yield`().
Scala Keywords
The following table lists Scala reserved keywords that cannot be used as variable names:
abstract
case
catch
class
def
do
else
extends
false
final
finally
for
forSome
if
implicit
import
lazy
match
new
null
object
override
package
private
protected
return
sealed
super
this
throw
trait
try
true
type
val
var
while
with
yield
-
:
=
=>
<-
<:
<%
>:
#
@
Scala Comments
Scala, like Java, supports single‑line ( //) and multi‑line ( /* … */) comments. Multi‑line comments can be nested, but each opening delimiter must have a matching closing delimiter. Comments are ignored by the compiler. Example:
object HelloWorld {
/* This is a Scala program
* This is a line comment
* This demonstrates a nested multi‑line comment
*/
def main(args: Array[String]) {
// Output Hello World
// This is a single‑line comment
println("Hello, world!")
}
}Blank Lines and Whitespace
A line that contains only spaces or comments is considered a blank line and is ignored by Scala. Tokens can be separated by spaces or comments.
Newlines
Scala is line‑oriented; statements can end with a semicolon ( ;) or a newline. The semicolon is usually optional. If a line contains a single statement, the semicolon can be omitted; if multiple statements appear on one line, they must be separated by semicolons. Example:
val s = "Beginner Tutorial"; println(s)Scala Packages
Defining Packages
Scala uses the package keyword to define packages. There are two ways to place code in a package:
package com.runoob
class HelloWorldor a C#‑style block:
package com.runoob {
class HelloWorld
}The second method allows multiple packages to be defined in a single file.
Imports
Scala uses the import keyword to reference packages. Imports can appear anywhere, not only at the top of the file, and their scope extends to the end of the enclosing block, reducing name‑collision possibilities.
import java.awt.Color // import Color
import java.awt._ // import all members of java.awt
def handler(evt: java.awt.event.ActionEvent) { // because java.awt is imported, the prefix can be omitted
...
}You can import selected members or rename them:
import java.awt.{Color, Font}
import java.util.{HashMap => JavaHashMap}
import java.util.{HashMap => _, _} // import all members except HashMapNote: By default, Scala always imports java.lang._ , scala._ , and Predef._ , which explains why packages starting with scala can be used without the scala. prefix.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Big Data Technology & Architecture
Wang Zhiwu, a big data expert, dedicated to sharing big data technology.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
