You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 91 Next »

What is Scala?

Scala is a modern language not unlike Groovy.
It is said to be more powerful (and faster) than Groovy or Ruby which has been the reason for its adoption at sites like Twitter.

Many of its features and paradigms favor multi-threading and concurrency. Some of these may not be unfamiliar to Objective-C and WebObjects developers. Here's a summary:

 

Objective-C

Java

Scala

Mutable/Immuable Datatypes

Collections e.g: NSArray/NSMutableArray

No

Yes

Closures

Blocks (Extension)

No

Anonymous Functions

Static variables

Yes

Yes

No

Static methods/functions

Yes

Yes

No

Concurrency

Grand Central Dispatch (Extension)

Threads

Actors

 

Weakly Typed

Strongly Typed

Strongly Typed

Other notable features include:

 

Objective-C

Java

Scala

Parametered methods

Yes e.g: addObject: to:

No

Yes e.g: add(object= ,to=)

Class composition

Categories

Interfaces

Traits

A fuller description of Scala can be found here.

Why Use Scala?

With Web 2.0, building concurrent WebObjects applications is a must.
Developing and maintaining a concurrent or multi-threaded WebObjects application can be challenging.

Scala offers concurrency that is (effectively) built-in to the language and is inherently thread-safe.
In other words, developing Ajax (i.e asynchronous communication) with WO will require concurrent request handling and thread-safe code, for which Scala is a better choice than Java.

In addition it may offer new solutions for concurrency in WebObjects and EOF.

Can WebObjects be Programmed In Scala?

Yes. It is very simple.
Scala compiles to java bytecode. Hence using it with WebObjects is fairly straightforward.

WebObjects In Scala

The following highlights some of the differences between Java and Scala in WebObjects:

EOs in Scala

Thread-Safe Shared Vars

Scala doesn't have static variables or methods. However, a class can have a Companion Object that will allow you to achieve something equivalent to static variables.
One of the advantages of this approach is that it is thread-safe, so you don't have to worry about synchronizing access to these fields in a concurrent application.

The following is an example of the use of a Companion Object for Talent in Scala instead of Talent static fields in Java.

Java:

public class _Talent extends EOGenericRecord {
	public static final String ENTITY_NAME	= "Talent";

Scala:

object Talent extends EOGenericRecord {
	val ENTITY_NAME = "Talent"

Compacted imports

Two lines in Java are compacted into one in Scala.

In Java:

import com.webobjects.eocontrol.EOGenericRecord;
import com.webobjects.eocontrol.EORelationshipManipulation;

In Scala:

import com.webobjects.eocontrol.{EOGenericRecord, EORelationshipManipulation}

WOComponents in Scala

Compact Constructors

Scala allows for simpler use of multi-valued constructors than Java.

In Java:

public class MenuHeader extends WOComponent {

    public MenuHeader(WOContext aContext) {
        super(aContext);
    }

In Scala:

class MenuHeader(context: WOContext) extends WOComponent(context: WOContext) {

Simplified Exception Handling

Scala doesn't force you to catch exceptions unlike in Java.
In addition, the syntax employs Scala's very powerful pattern matching to handle different exceptions.

In Java:

try {
    EditPageInterface epi = D2W.factory().editPageForNewObjectWithEntityNamed(_manipulatedEntityName, session());
    epi.setNextPage(context().page());
    nextPage = (WOComponent) epi;
} catch (IllegalArgumentException e) {
    ErrorPageInterface epf = D2W.factory().errorPage(session());
    epf.setMessage(e.toString());
    epf.setNextPage(context().page());
    nextPage = (WOComponent) epf;
}

In Scala:

try {
     var epi: EditPageInterface = D2W.factory.editPageForNewObjectWithEntityNamed(_manipulatedEntityName, session)
     epi.setNextPage(context.page)
     nextPage = epi.asInstanceOf[WOComponent]
} catch {
     case e: IllegalArgumentException => {
            var epf: ErrorPageInterface = D2W.factory.errorPage(session)
            epf.setMessage(e.toString)
            epf.setNextPage(context.page)
            nextPage = epf.asInstanceOf[WOComponent]
     }
}

Scala Annotations vs. Generic Accessors

An example of accessing variables in WebObjects with the following languages:

 

Objective-C

Java

Scala

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="317a87f2-8e5f-4ef2-9df0-68e06e7c01a7"><ac:plain-text-body><![CDATA[

getter

[object name]

object.name()

object.name

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="7b9c8c3c-03dd-4ad7-abec-07cde281f20b"><ac:plain-text-body><![CDATA[

setter

[object setName:aName]

object.setName(aName)

object.name = aName

]]></ac:plain-text-body></ac:structured-macro>

Of course in Java, we may generate WebObjects classes with "get" methods as well in order to stick to convention.
In scala there is an additional convenience we may use to produce "get" and "set" methods in addition to the default Scala accessors - Scala Annotations.

E.g, in Main.scala we annotate our component keys with @BeanProperty to automatically create public "set" and "get" methods.
These variables can then be accessed via KVC.

@BeanProperty var username = new String()
@BeanProperty var password = new String()
@BeanProperty var isAssistantCheckboxVisible = false

How to Use Scala Collections with EOF

One of the benefits of Scala is its very powerful, concurrency-ready collection classes - primarily List, Map, Seq and Set.
Employing these instead of NSArray and NSDictionary in WebObjects/EOF may be challenging.

But one may modify the EO templates to produce API such as:

def movies: NSArray[EOGenericRecord] = {
    storedValueForKey(_Studio.Keys.MOVIES).asInstanceOf[NSArray[EOGenericRecord]]
}
  
def moviesList: List[EOGenericRecord] = {
    movies.objects.toList
}

How to Add Scala to a WO Project

  1. Install the Scala eclipse IDE
  2. Add Scala support to your WO project:
    1. Right-click your project in the WO Explorer
    2. In the context menu select Configure -> Add Scala Nature
  3. Convert to or use .scala instead of .java source

Note

This is for Eclipse/WOLips IDE

WO Scala Example

The following example is an almost 100% Scala WO app. In reality it is a mixed Java/Scala app:
All the EO logic and WO components are in Scala.
Only the Application class is Java.

It is based on the D2W Movies example.

No files shared here yet.

Setup

  1. Install the Scala eclipse IDE
  2. Install and start the OpenBase OBMovies database.
  3. Right-click on Application.java and run as a WOApplication (as usual).

EO Templates

When you create your .eogen file, be sure to make the following changes in the EOGenerator Editor:

  1. Point to the local Scala versions of the .eotemplate files for Entity and _Entity
  2. Change the File Names Extension to "scala"
  3. In Destination Paths set the Superclass Package (e.g: base)
  4. Uncheck Java under Options

How to Build & Deploy a WebObjects Scala Project with Ant

  1. Download an install Scala
  2. The scala.home (the location Scala has been installed onto) to the project build.properties file
  3. Add the scalac tasks to the ant build.xml file
  4. Customise the app classpath file. i.e either MacOSClasspath.txt or UNIXClasspath.txt. You will need to add an entry for scala-library.jar
  • No labels