Access Modifiers: Scala & Java (II – Java Examples)

In our last post, we discussed about the access modifiers in Java and in Scala. As btilford noticed, there were no examples in that post, this post is supposed to cover the Java part.

In order to better understand how access modifiers works, we have to introduce the main classes. There will be one public class and one with the default access modifier.

Main Classes

package com.wordpress.j2eethoughts.accessModifiers.a; public class PublicFooClass { public int publicBar=0; protected int protectedBar=0; int defaultBar=0; private int privateBar=0; public void doStuff(){ PublicFooClass pubFoo = new PublicFooClass(); System.out.println(pubFoo.publicBar); System.out.println(pubFoo.protectedBar); System.out.println(pubFoo.defaultBar); System.out.println(pubFoo.privateBar); } public void doStuff2(){ System.out.println(publicBar); System.out.println(protectedBar); System.out.println(defaultBar); System.out.println(privateBar); } }
package com.wordpress.j2eethoughts.accessModifiers.a; class DefaultFooClass { public int publicBar=0; protected int protectedBar=0; int defaultBar=0; private int privateBar=0; public void doStuff(){ DefaultFooClass defFoo = new DefaultFooClass(); System.out.println(defFoo.publicBar); System.out.println(defFoo.protectedBar); System.out.println(defFoo.defaultBar); System.out.println(defFoo.privateBar); } public void doStuff2(){ System.out.println(publicBar); System.out.println(protectedBar); System.out.println(defaultBar); System.out.println(privateBar); } }

These two classes haven’t any compilation error. Now it’s time to make the compiler talk.

Basic Use

package com.wordpress.j2eethoughts.accessModifiers.a; public class TestClass { public static void test(){ //public class PublicFooClass pubFoo = new PublicFooClass(); System.out.println(pubFoo.publicBar); System.out.println(pubFoo.protectedBar); System.out.println(pubFoo.defaultBar); System.out.println(pubFoo.privateBar);//does not compile! //default class DefaultFooClass defFoo = new DefaultFooClass(); System.out.println(defFoo.publicBar); System.out.println(defFoo.protectedBar); System.out.println(defFoo.defaultBar); System.out.println(defFoo.privateBar);//does not compile! } }

Logically, the private fields are not visible for this TestClass. Protected, default, and public fields are visible because all classes lay in the same package.
If we move this class to another package, the compiler will complaint again.

package com.wordpress.j2eethoughts.accessModifiers.b; import com.wordpress.j2eethoughts.accessModifiers .a.PublicFooClass; public class TestClass { public static void main(){ //public class PublicFooClass pubFoo = new PublicFooClass(); System.out.println(pubFoo.publicBar); System.out.println(pubFoo.protectedBar);// does not compile! System.out.println(pubFoo.defaultBar);// does not compile! System.out.println(pubFoo.privateBar);// does not compile! //default class DefaultFooClass defFoo = new DefaultFooClass();// does not compile! System.out.println(defFoo.publicBar);// does not compile! System.out.println(defFoo.protectedBar);// does not compile! System.out.println(defFoo.defaultBar);// does not compile! System.out.println(defFoo.privateBar);// does not compile! } }

The DefaultFooClass is not visible at all for this class, because they don’t share the same package. The same rule applies for the protected and default fields of PublicFooClass.

Inheritance

There is another scope we haven’t analysed yet, the visibility in inheritance. We will extend the PublicFooClass in two different packages, discovering so the different ways that compiler complaints.
Firstly, we will implement a class extending PublicFooClass laying in the same package:

package com.wordpress.j2eethoughts.accessModifiers.a; public class SubPubFooClass extends PublicFooClass { public void doStuff(){ PublicFooClass pubFoo = new PublicFooClass(); System.out.println(pubFoo.publicBar); System.out.println(pubFoo.protectedBar); System.out.println(pubFoo.defaultBar); System.out.println(pubFoo.privateBar);// does not compile! } public void doStuff2(){ System.out.println(super.publicBar); System.out.println(super.protectedBar); System.out.println(super.defaultBar); System.out.println(super.privateBar);// does not compile! } }

As they share the same package, only private fields are not visible. So in this case, there is no difference (in visibility terms) between extending the class or not.
What will happen if the subclass lays in a different package?

package com.wordpress.j2eethoughts.accessModifiers.b; import com.wordpress.j2eethoughts.accessModifiers.a.PublicFooClass; public class SubPubFooClass extends PublicFooClass { public void doStuff(){ PublicFooClass pubFoo = new PublicFooClass(); System.out.println(pubFoo.publicBar); System.out.println(pubFoo.protectedBar);// does not compile! System.out.println(pubFoo.defaultBar);// does not compile! System.out.println(pubFoo.privateBar);// does not compile! } public void doStuff2(){ System.out.println(super.publicBar); System.out.println(super.protectedBar); System.out.println(super.defaultBar);// does not compile! System.out.println(super.privateBar);// does not compile! } }

In this case, we find some interesting compiler errors. In doStuff2 method we have the expected errors. Private fields are inaccessible by definition, and default fields are not visible because they don’t share the same package. Now, let’s focus on the first method. Why do the compiler find more errors in this case? Because the field is accessed from outside the object. In other words, the object that access this field, doesn’t own it, so it’s invisible in its eyes.

Inner Classes

In this last group of examples, we will focus on the Inner Classes and its visibility. The first thing we need is a class with some Inner Classes.

package com.wordpress.j2eethoughts.accessModifiers.a; public class FooClass { public int publicBar=0; protected int protectedBar=0; int defaultBar=0; private int privateBar=0; public void doStuff(){ System.out.println(publicBar); System.out.println(protectedBar); System.out.println(defaultBar); System.out.println(privateBar); PubBarClass pub = new PubBarClass(); ProBarClass pro = new ProBarClass(); DefBarClass def = new DefBarClass(); PriBarClass pri = new PriBarClass(); pri.doStuff(); } public ProBarClass getProBarClass(){ return new ProBarClass(); } public class PubBarClass{ public void doStuff(){ System.out.println(publicBar); System.out.println(protectedBar); System.out.println(defaultBar); System.out.println(privateBar); } } protected class ProBarClass{ public void doStuff(){ System.out.println(publicBar); System.out.println(protectedBar); System.out.println(defaultBar); System.out.println(privateBar); } } class DefBarClass{ public void doStuff(){ System.out.println(publicBar); System.out.println(protectedBar); System.out.println(defaultBar); System.out.println(privateBar); } } private class PriBarClass{ private void doStuff(){ System.out.println(publicBar); System.out.println(protectedBar); System.out.println(defaultBar); System.out.println(privateBar); } } }

We have one Inner Class for each type of modifier, this way, it will be easy to analyse what is possible and what is not. In this example, we can see that it’s possible to access outer class’ private fields from the inner class and vice-versa. Afterwards, we will test the visibility of the Inner Classes.

package com.wordpress.j2eethoughts.accessModifiers.a; import com.wordpress.j2eethoughts.accessModifiers .a.FooClass.DefBarClass; import com.wordpress.j2eethoughts.accessModifiers .a.FooClass.ProBarClass; import com.wordpress.j2eethoughts.accessModifiers .a.FooClass.PubBarClass; public class TestInner { public static void test(){ PubBarClass pub = new PubBarClass(); ProBarClass pro = new ProBarClass(); DefBarClass def = new DefBarClass(); PriBarClass pri = new PriBarClass();//does not compile! } }

As this class stands in the same package, all Inner Classes but the private are accessible.
If we move this class to another package we will get more errors.

package com.wordpress.j2eethoughts.accessModifiers.b; import com.wordpress.j2eethoughts.accessModifiers .a.FooClass.PubBarClass; public class TestInner { public static void test(){ PubBarClass pub = new PubBarClass(); FooClass foo = new FooClass(); ProBarClass pro = foo.getProBarClass(); //does not compile! ProBarClass pro2 = new ProBarClass();//does not compile! DefBarClass def = new DefBarClass();//does not compile! PriBarClass pri = new PriBarClass();//does not compile! } }

Only PubBarClass is visible, because this client doesn’t share neither package and ancestor with the Inner Classes. However, if we extend the ancestor class FooClass we will get different errors.

package com.wordpress.j2eethoughts.accessModifiers.b; import com.wordpress.j2eethoughts.accessModifiers.a.FooClass; public class TestInnerExtends extends FooClass { public void test(){ PubBarClass pub = new PubBarClass(); ProBarClass pro2 = getProBarClass(); ProBarClass pro = new ProBarClass();//does not compile! DefBarClass def = new DefBarClass();//does not compile! PriBarClass pri = new PriBarClass();//does not compile! } }

The instantiation of ProBarClass doesn’t compile because there is no user defined constructor, so the compiler adds automatically a protected one (the class is protected), thus it’s not visible for this client class because it doesn’t extend that ProBarClass. At this point, you would have deduced why the default and private classes are not accessible.

We hope all these examples could explain clearly what it can be done, and what can’t, with the access modifiers.

Advertisements

Access Modifiers: Scala & Java

In this post we will analyse the differences and the similarities between access modifiers in Scala and Java. Despite Scala is compatible with Java, there are some differences.

Java

In Java there are four types of access modifiers:

  • public: this is the less restrictive access modifier. Classes, methods, inner classes and fields can be declared public. Every class in every package can access the element declared public.
  • protected: methods, inner classes and fields can be declared protected. Only subclasses or classes in the same package can access the element declared protected.
  • default: classes, methods, inner classes and fields can be declared with no access modifier. Only classes in the same package can access the element declared with no modifier.
  • private: this is the most restrictive modifier. Methods, inner classes and fields can be declared private. Only the own class can access the elements declared private. Private methods or fields existing in an inner class can be accessed by the outer class.

Let’s make it more visual:

Modifier Class Package Subclass Every class
public Y Y Y Y
protected Y Y Y N
default Y Y N N
private Y N N N

Scala

In Scala there are three types of access modifiers (default that behaves like public, protected and private) but they can be augmented with qualifiers (only protected and private can). This qualification means that access is protected or private up to a scope.

First we will explain the unqualified access modifiers:

  • default: this is the less restrictive one, it behaves like public in Java. Classes, methods, inner classes and fields can be declared with no modifier. Every class in every package can access the element declared with no modifier.
  • protected: a member declared protected can be accessed only by its subclasses. This access modifier is more restrictive than its analogous in Java.
  • private: this is the most restrictive modifier. A member declared private can be accessed only by the owner class. This also applies for inner classes. In other words a private member is visible inside the own class and inside any deeper inner class. This rule only applies downwards, so a private member defined in an inner class can not be accessed by any outer class (this is possible in Java).

Let’s see the table:

Modifier Class Package Subclass Every class
default Y Y Y Y
protected Y N Y N
private Y N N N

Right now you could be wondering how to make a member visible for any class in the same package. The answer is scoped access modifiers. As we said, private and protected access modifiers can be qualified with a name of a package or class (scope). Generally scoped private and scoped protected access modifiers behave the same way, except under inheritance when declared on class members. The scope is defined between square brackets.

When the scope of protected or private is a package, the visibility is similar to package visibility in Java (default). Given a class X defined inside the package a.b.c, a member defined with protected[a] (or private[a]) is visible within package a. If you want the same behaviour than default visibility in Java, you must specify protected[c] (or private[c]).

When the scope is a class, the visibility is similar to private with some considerations. Given a class X with an inner class Y, a member in Y defined as protected[X] (or private[X]) behaves identically to private in Java. Otherwise, when defined as protected[Y] (or private[Y]) behaves identically to private in Scala.

There is yet another scope, this, that gives the most restrictive access modifier that exists. When a member of a class is defined as protected[this] (or private[this]), it is illegal to access this member outside the object. In other words, given private[this] var foo = 3, foo only can be accessed this way: this.foo.

Previously we said that scoped protected and private behave identically except under inheritance. The only difference is that scoped protected is less restrictive because, independently of the scope stated, a member defined with protected[something] is visible for any subclass, while when defined with private[something] is not.

Sorting Algorithms Comparison and Quicksort example

Today I’ve remembered those days back in University, when we learned Algorithms and Data Structures. Among the big amount of algorithms we studied, there were the sorting algorithms. The first algorithm introduced was the Bubble Sort, the worst efficient one. Afterwards, the most efficient algorithms were introduced: Merge Sort and Quicksort. Let’s remember the basics of these algorithms.

Bubble Sort

This is the simplest algorithm, however it’s the worst one in performance speaking. The average and worst case complexity are both O(n2). But there is good news, its complexity, for the best case, is only O(n). Here there is an animation that explains how it works: Bubble Sort Animation.

Merge Sort

The Merge Sort algorithm is better than Bubble Sort. The average and worst case complexity is O(nlogn). The best case (when the array is sorted) is also O(nlogn), but with some optimizations can be reduced to O(n). Here you can find another animation Merge Sort.

Quicksort

The Quicksort algorithm is usually faster than Merge Sort, despite they have the same average case complexity O(nlogn). However, the complexity for the worst case is O(n2), with some improvements it can be reduced. Here there is an animation: Quicksort.

Implementation Quicksort

After this brief comparison between sorting algorithms, let’s see the implementation of Quicksort algorithm in Java and Scala.

Java

This is the implementation in Java of the Quicksort algorithm:

public static void sort(int[] xs){ sort(xs,0,xs.length-1); } public static void sort(int[] xs, int left, int right){ int pivot = xs[(left+right)/2]; int i = left; int j = right; while(i <= j){ while(xs[i] < pivot){ i++; } while(xs[j] > pivot){ j++; } if(i<=j){ int sw = xs[i]; xs[i] = xs[j]; xs[j] = sw; i++; j--; } } if(left < j){ sort(xs,left,j); } if(j < right){ sort(xs,i,right); } }

Scala

First the algorithm in a no functional way, as you could see, this implementation is equivalent to Java’s:

def sort(xs: Array[Int]) { def swap(i: Int, j: Int) { val t = xs(i); xs(i) = xs(j); xs(j) = t } def sort1(l: Int, r: Int) { val pivot = xs((l + r) / 2) var i = l; var j = r while (i <= j) { while (xs(i) < pivot) i += 1 while (xs(j) > pivot) j -= 1 if (i <= j) { swap(i, j) i += 1 j -= 1 } } if (l < j) sort1(l, j) if (j < r) sort1(i, r) } sort1(0, xs.length - 1) }

And now, let’s rewrite it in a functional way:

def sort(xs: Array[Int]): Array[Int] = { if (xs.length <= 1) xs else { val pivot = xs(xs.length / 2) Array.concat( sort(xs filter (pivot >)), xs filter (pivot ==), sort(xs filter (pivot <))) } }

Getters & Setters and its goodness and evilness

If you are a DZone reader, you will have read many posts about getters and setters and its evilness. Getters and setters are the response to an old Object Oriented principle which says that object’s implementation must not be exposed. On the other hand, there is also another old principle called Uniform Access Principle which says that client code should not be affected by a decision to implement an attribute as a method or field. Unfortunately, Java doesn’t follow this last principle.

Don’t Expose the Implementation

Currently, the most used IDE’s can generate the getters and setters for fields. Sometimes this doesn’t help, and developers automatically generate unnecessary getters and/or setters. This next example could be seen as a situation where generating getters and setters automatically is a bad practice:

package com.wordpress.j2eethoughts.ooPrinciples; public class Odometer{ private BigDecimal total; private BigDecimal partial; public Odometer (){ total = BigDecimal.ZERO; partial = BigDecimal.ZERO; } public BigDecimal getTotal(){ return total; } public void setTotal(BigDecimal total){ this.total = total; } public BigDecimal getPartial(){ return partial; } public void setPartial(BigDecimal partial){ this.partial = partial; } }

Now let’s explain because this is a bad practice. Maybe at a first glance, you may think that this implementations satisfies the principle of not expose the internal implementation of the object. Unfortunately, this is not true, everything is exposed. There isn’t much difference between this implementation with getters and setters and the hypothetical implementation with public fields. In addition, you can do illegal things with this implementation, as decrement the number of Kilometres of the Odometer. The unique advantage between this implementation and one with public fields is that you could attach some functionality in any function, like logging, checking permissions…

A more correct implementation for this class would be:

package com.wordpress.j2eethoughts.ooPrinciples; public class Odometer{ private BigDecimal total; private BigDecimal partial; public Odometer (){ total = BigDecimal.ZERO; partial = BigDecimal.ZERO; } public BigDecimal getTotal(){ return total; } public BigDecimal getPartial(){ return partial; } public void resetPartial(){ partial = BigDecimal.ZERO; } public void increment(BigDecimal inc){ partial.add(inc.abs()); total.add(inc.abs()); } }

This class implementation ensures that nothing wrong is done with the Odometer, Kilometres can only increase and you can’t rig the Odometer decreasing the total amount of Kilometres made.

Uniform Access Principle

As we have explained before, Java doesn’t satisfy the Uniform Access Principle, for this reason we will explain it using Scala. The client code must not be affected if the developer decides to implement an attribute as a method or as a field. For illustrating this example we will use a Circle class. There will be two different implementations for the attributes perimeter and area.

package com.wordpress.j2eethoughts.uap import Math.Pi class CircleVal (radius : Int){ val perimeter = 2 * Pi * radius val area = Pi * radius * radius } class CircleDef (radius : Int){ def perimeter = 2 * Pi * radius def area = Pi * radius * radius }

The client uses these classes exactly the same way in both implementations. The client doesn’t care if the developer had decided to implement these attributes as methods or as fields.

package com.wordpress.j2eethoughts.uap object Main { def main(args : Array[String]) : Unit = { val c1 = new CircleVal(4) println(c1.perimeter) println(c1.area) val c2 = new CircleDef(4) println(c2.perimeter) println(c2.area) } }

This post is not supposed to decide about the evilness or goodness of getters and setters, its only intention is to think about its use. So, we would be very glad if after reading this post, you think twice before ask your IDE to automatically generate the getters and setters.

Scala: Overloading Operators

If you come from Java I have just caught your attention. If you are a C++ developer you might be not surprised.

In Scala, every operator is actually a method. The difference between methods and operators is how you use them. When you write:

val = 3 + 5

Scala calls the method + defined in Int:

val = (3).+(5)

In the first example + is used as operator, in the second one, + is used as a method.
As said, every operator is a method, which means that we can call any method as an operator. For instance, this two instructions are equivalent:

val test1 = “Alice” startsWith “A”
val test2 = “Alice”.startsWith(“A”)

After reading this, you might be wondering: Scala doesn’t really have operator overloading, it is only method overloading. Well, maybe it’s true, but from the language point of view, it is operator overloading!

There are three types of operators, infix, prefix and postfix. In Scala you can implement these three kinds, but there are some restrictions about the prefix and postfix operators.

Infix

In infix notation, you put the operator between the objects. This kind of operators could take two or more operators. When having more than two, all but the first go after operator between parenthesis.
Now let’s do a real example where it could be useful this infix operator overloading.

class Angle (d: Int, m: Int, s: Int) { require (d < 360 && m <60 && s < 60) val degree: Int = d val minute: Int = m val second: Int = s def + (that: Angle) : Angle = { val sec = second + that.second val min = minute + that.minute + (sec /60) val deg = degree + that.degree + (min /60) new Angle (deg % 360,min % 60,sec % 60) } def + (deg: Int) : Angle = new Angle (degree + deg % 360, minute, second) def - (that: Angle) : Angle = { val thisSecs = degree * 3600 + minute * 60 + second val thatSecs = that.degree * 3600 + that.minute * 60 + that.second val dif = if(thisSecs <= thatSecs) thisSecs - thatSecs else thatSecs - thisSecs val min = dif / 60 val deg = min /60 new Angle (deg , min % 60, dif % 60) } override def toString = degree+ "º "+minute+"' "+second+"''" }

After creating this class, we can add and subtract angles as follows:

val angle1 = new Angle(40,30,35)
val angle2 = new Angle(30,52,50)
val angle3 = angle1 + angle2
println(angle3)
println(angle1 – angle2)
println(angle2 – angle1)
println(angle3 – angle1)

And the result is:

71º 23′ 25”
9º 37′ 45”
9º 37′ 45”
30º 52′ 50”

This example above is only a proof of concept of operator overloading. Maybe it’s not programmed in a functional way, but I’ve done my best. Any comments are appreciated.

Prefix

In prefix notation, you put the operator before the object. In Scala, the prefix operators can only take one operator, this is called unary operator. The only identifiers that can be used in unary prefix operators are +, , ! and ~. If you need to define a prefix operator, for instance, !, you must implement a method called unary_!.

Postfix

In postfix notation, you put the operator after the object. This kind of operators are also unary. Unlike the prefix operators, in postfix operators there is no restriction about the names of the methods/operators. The convention about postfix operators is invoking the operators without parenthesis only if the operator has no side effects, otherwise, you might include them. For example, method toLowerCase defined in String should be invoked without parenthesis and println() should be invoked with parenthesis because it writes to the Console.

XStream

XStream is a library to serialize objects to XML and vice versa. It must not be used as a XML processor.

The way that XStream serializes and de-serializes objects is by using Annotations. This post will show you how to annotate a class and how to serialize it.

First of all let’s introduce the class:

public class Book { private String isbn; private List author; private String title; private int pages; //class continues... }

This class models a book. It has the ISBN, a list of authors (it’s only a String per author), the title and the number of pages. The point of XStream is that it uses reflection to serialize and de-serialize the objects.
We want to serialize this book to this XML:

<BOOK> <ISBN>978-0-9815316-0-1</ISBN> <AUTHOR>Martin Odersky</AUTHOR> <AUTHOR>Lex Spoon</AUTHOR> <AUTHOR>Bill Venners</AUTHOR> <TITLE>Programming in Scala</TITLE> <PAGES>736</PAGES> </BOOK>

The next step is to annotate the class:

package com.wordpress.j2eethoughts; import com.thoughtworks.xstream.annotations.XStreamAlias; import java.util.List; @XStreamAlias("BOOK") public class Book { @XStreamAlias("ISBN") private String isbn; //no annotations private List author; @XStreamAlias("TITLE") private String title; @XStreamAlias("PAGES") private int pages; //class continues... }

Note that lists must not be annotated. After this, we need to create the facade of XStream:

package com.wordpress.j2eethoughts; import java.util.ArrayList; import java.util.List; import com.thoughtworks.xstream.XStream; public class Main { public static void main(String[] args) { XStream xs = new XStream(); xs.processAnnotations(Book.class); xs.addImplicitCollection(Book.class, "authors", "AUTHOR", String.class); List authors = new ArrayList(); authors.add("Martin Odersky"); authors.add("Lex Spoon"); authors.add("Bill Venners"); Book book = new Book("978-0-9815316-0-1", authors,"Programming in Scala", 736); System.out.println(xs.toXML(book)); } }

And that’s all, now you can serialize any Book object. For de-serialization you must call the method xs.fromXML passing a String to the method.

Scala: Hello World!

Nowadays, there are many languages running on the Java Virtual Machine, but in the beginning, the JVM could run only compiled Java programs, now we have plenty full of new languages, some of them designed expressly for the JVM, others that had a version capable of running on it.

People is wondering which will be the Next Big JVM Language. There are many candidates who fight for being the chosen one. Scala, JRuby, Jython, Groovy, Clojure are among them.

Recently, a great book came to my hands, Programming in Scala. A comprehensive step-by-step guide, it’s co-authored by Martin Odersky, Lex Spoon and Bill Venners. Mr. Odersky is the creator of the Scala language and also the co-designer of Java generics. In this post, a Hello World example in Scala will be made.

The very first thing to do is download the Scala distribution, you can find it here. The last stable release is 2.8.0. Now the Scala interpreter is installed in our system. With this interpreter, our first Scala program can be done and executed.

Scala is an Object Oriented and a functional programming language. It can be executed within a Java code and vice versa. The semicolon at the end of each instruction is optional, so you don’t have to put it at the end of every sentence. It is less verbose than Java, thus some type declarations can be omitted. For instance, you can say:

var x = new HashMap[int, String]()

Instead of:

var x Map[int, String]() = new HashMap[int, String]()

These are only a few characteristics of Scala. Now,let’s continue with some glossary:

  • val: It’s a variable that could not be modified, it’s like a final variable in Java. Once assigned, it can’t be reassigned
  • var: It’s a variable, it can be modified
  • def: It defines a function
  • print and println: prints the passed the String to the standard output. It’s similar to System.out.println in Java
  • while: the instruction for loops
  • if: the instruction for deciding
  • (paramName1 : Type, paramName2 : Type => paramName1 + paramName2): also is the format of literal functions.
  • foreach (element => action) : the instruction for iterations
  • for (element <- elements): another instruction for iterations, element is a val not a var

Let’s put it all together. The first example is a simple Hello World!. Put the following code into a file named hello.scala

println(“Hello World!”)

Then from the OS prompt, execute:

$> scala hello.scala

The result will be:

Hello World!

Let’s make a more sophisticated sample. Definition of factorial function and execution with the first number typed in the standard input.

def factorial ( x : Int ) : Int = { if ( x == 0 ) 1 else x * factorial ( x - 1 ) } println(factorial(args(0).toInt))

And yet, another example. Capitalize the words typed in the standard input.

args.foreach(arg => print(arg.capitalize))

Executing this:

$> scala capitalize.scala hello world !

The output will be:

HelloWorld!