Channels ▼


Scala for C# Developers: A Tutorial

In Scala, you can perform mixin-class composition. That is, you can reuse new member definitions of a class that represent the delta with its superclass in the definition of the new class. I'll dive deeper on traits and mixin-class composition with clear examples later. Now that I've defined traits, let me go back to our sample FirstApplication singleton object.

If you add a line that starts with the override keyword to the FirstApplication object definition, you will override the main method defined in the App trait with your own implementation:

  object FirstApplication extends App {
      override def main(args: Array[String]) = Console.println("Let's put some text on the Console output.")

While you write the new line of code in the editor, you can take advantage of auto-complete features. For example, if you enter "Console." and wait a moment, the IDE displays all members for Console. Press p and the context menu will display all members for Console that start with "p" (see Figure 8). You can also press Ctrl + Space in the editor to show Scala completions (the same shortcut you use in Visual Studio).

Using the auto-complete feature in Scala
Figure 8: Using the auto-complete features to filter the members for Console that start with "p."

As you might guess, Console is a singleton object. Console implements functionality for printing Scala values on the terminal and for reading specific values. You can right-click on Console and select Open Declaration in the context menu. The IDE will open a new code tab and display the declaration for the Console singleton object (see Figure 9).

The declaration of a singleton object
Figure 9: The declaration of the Console singleton object.

In Scala, it is necessary to use the def keyword to declare a method. Because the main method in the FirstApplication object overrides the main method defined in the App trait, it is necessary to include the override keyword. You will notice that a green arrow appears at the left-hand side of the line that overrides the main method. When you hover the mouse over the green arrow, a tooltip displays the label "overrides scala.App.main," and the mouse pointer changes to a hand (Figure 10).

code editor in Scala
Figure 10: The code editor displaying details about the overridden main method.

You can click on the green arrow and the editor will navigate to the App trait and display the code for the main method (see Figure 11) that the FirstApplication trait is overriding. Both Eclipse and the Scala IDE include many features that would require you to install or buy plug-ins in Visual Studio 2012. As a result, you won't be disappointed by the IDE feature set when you start working with Scala.

code editor for main in Scala
Figure 11: The code editor displaying the code for the main method in the App trait.

If you've worked with Delphi, the way you specify the method arguments and types in Scala will feel familiar. The argument name goes first, then the type, separated by a colon. The main method receives an args argument of type Array[String]. Array[String] is equivalent to Array<String> in C#. Thus, Array[T] is equivalent to Array<T> in C#, where T is the desired type for the array elements. Arrays are zero based, as in C#, but you have to specify an index in parenthesis instead of square brackets. For example, you can use args(0) to access the first element in the Array[String] argument named args.

The method doesn't return any value, so it isn't necessary to specify the return type. By default, a method that doesn't specify a return type has a Unit return type, which is equivalent to the well-known void in C#. You can specify a return type of Unit if you want to, so the following method declaration would be equivalent to the previous declaration:

 override def main(args: Array[String]): Unit

Notice that you specify the return type, separated by a colon, after the closing parenthesis. If you are curious about the rationale for types appearing after the arguments, variables, and methods, I suggest you watch Martin Odersky's talk at FOSDEM 2009, where he describes the design principles of the Scala programming language. Odersky, who developed Scala, also explained this design in his interview with Dr. Dobb's. In both cases, he provides a clear example of the problems that modern complex types generate for type-interference mechanisms. Many developers coming from C, C++, C#, or Java backgrounds hate reading type declarations in a different way. If you listen to Odersky's detailed explanation, you may not fall victim to this hatred for type declarations in Scala.

For example, in modern applications, it is common to find complex types such as Services.EnterpriseLibrary.Common.UpdateCustomerRequest. When you put the type before the method declaration, argument, or variable, you aren't just including a short word such as int, byte, or long, as was traditional in early C programs. Once you get used to the way Scala has been designed, it is easier to read and understand code containing complex type names, and the type-inference mechanism can work more efficiently.

After the main method declaration, you will notice an equal sign (=) and then a single line of code that calls the println method for the Console singleton object. Because there is just one statement in the code block for the method, the usage of curly braces is optional. Thus, the following two code blocks produce the same results and are valid:

// Option 1: Single statement without curly braces
object FirstApplication extends App {
	override def main(args: Array[String]) = Console.println("Let's put some text on the Console output.")

// Option 2: Single statement with curly braces
object FirstApplication extends App {
	override def main(args: Array[String]) = 
           Console.println("Let's put some text on the Console output.")

Scala allows you to use semicolons as in C#. However, Scala has the ability to infer semicolons, so they are optional. You only need them when multiline statement separations might not work as you expect, and you don't want to reorganize your lines based on the way the inference mechanism works. The following code block uses the optional semicolon and makes the code similar to what you'd expect when working with C#. Obviously, it is convenient to reduce semicolon usage in Scala because you won't find too many semicolons when you read Scala code written by the language experts.

object FirstApplication extends App {
	override def main(args: Array[String]) = 
           Console.println("Let's put some text on the Console output.");

Executing a Simple Scala Application and Running Code in the Interpreter

Let's return to our sample FirstApplication. Select Run | Run or just press Ctrl + F11 and FirstApplication will execute its main method, which displays text on the Console output. If there are problems in the build, you will see the list in the Problems view and the errors highlighted in the code editor for the different source files. You can check the Problems view by selecting Window | Show View | Problems or pressing Alt + Shift + Q, X (see Figure 12).

The Problems view displaying details for three errors
Figure 12: The Problems view displaying details for three errors.

If you run the previously shown code (which doesn't have errors), the IDE will display "Let's put some text on the Console output" in the Console view (see Figure 13). If you don't see the Console view, you just need to select Window | Show View | Console or press Alt + Shift + Q, C. Then, make sure that the "Show console when standard out changes" option button is pressed (see Figure 14). This way, the IDE will automatically display the Console whenever your application writes text to it.

The tooltip text
Figure 13: The Console view displaying the results of running the simple FirstApplication Scala application.

The Console view
Figure 14: The "Show console when standard out changes" option button displaying its tooltip text.

One of the best features of the Scala IDE is that it allows you to run a stand-alone piece of code in the integrated Scala interpreter. If you've worked with F#, you already know about the F# interactive window. You can take advantage of this REPL (Read-Evaluate-Print Loop) mechanism to test different pieces of code without having to build the entire application. For example, if you select the following piece of code "Console.println("Let's put some text on the Console output.");" in the editor for the FirstApplication trait, and then press Ctrl + Shift + X or click the Run selection in Scala interpreter button, the IDE will display the Scala Interpreter view, evaluate the selected code, and print the results of the evaluation. In this case, the result of the evaluation will be displaying the text (see Figure 15).

The Scala interpreter displaying the results of executing the selected code
Figure 15: The Scala interpreter displaying the results of executing the selected code.


In this article, I've provided a brief overview about the Scala IDE for those used to spending their days with Visual Studio. In addition, I've gotten you up and running with Scala. Obviously, I still need to dive deep into the differences between Scala and C#, but I wanted to offer a quick introduction and help you start working with a completely new IDE.

In the next article, I'll discuss the unique way Scala works with immutable and mutable variables, method names, operators, and type inference, and you'll see why Scala is becoming so popular.

Gaston Hillar is a frequent contributor to Dr. Dobb's.

Related Article

Scala for C# Developers: Useful Features

Related Reading

More Insights

Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.