Dienstag, 6. Oktober 2009

learning Scala

This tutorial based on:
http://www.scala-lang.org/docu/files/ScalaTutorial.pdf
http://www.thomasknierim.com/77/scala/scala-tutorial-2/



write a file s1.scala

object HelloWorld {
def main(args: Array[String]) {
println("Hello, world!")
}
}


object -> declare a static singleton object
args: Array[String] -> a variable args as Array of Strings

compile and execute

$ scalac s1.scala
$ ls
s1.class s1$.class s1.scala


you get created standard java class files, but you must use java interpreter with setted parameters.


$ java s1
Exception in thread "main" java.lang.NoClassDefFoundError: scala/ScalaObject
at java.lang.ClassLoader.defineClass1(Native Method)
....

$ file /usr/bin/scala
$ /usr/bin/scala: POSIX shell script text executable
$ cat /usr/bin/scala
#!/bin/sh

JAVA_DIR=/usr/share/java
LIB_CLASSPATH=$JAVA_DIR/scala-library.jar:$JAVA_DIR/scala-compiler.jar:$JAVA_DIR/jline.jar

exec ${JAVACMD:=java} ${JAVA_OPTS:=-Xmx256M -Xms16M} \
-Xbootclasspath/a:$LIB_CLASSPATH \
-classpath .:$CLASSPATH:$LIB_CLASSPATH \
scala.tools.nsc.MainGenericRunner \
"$@"

$ scala s1
hallo


As you can see, the scala executable is a simple shell script, which start the java virtual machine with specific parameters and the scala library.


Create Date.scala

import java.util.{Date, Locale}
import java.text.DateFormat
import java.text.DateFormat._
object FrenchDate {
def main(args: Array[String]) {
val now = new Date
val df = getDateInstance(LONG, Locale.FRANCE)
println(df format now)
}
}








import java.util.{Date, Locale} import Date and Locale from java.util
import java.text.DateFormat._ DateFormat._ is similar to DateFormat.* in java
val declare an inmutable variable
val now = new Date simmilar to "Date now = new Date();" in java
println(df format now) "df format now" is similar to "df.format(now)"




In scala is everything an object. There is no primitive datatypes (that is similar to ruby).

Because scala based on functional programming functions are objects too.


object Timer {

def oncePerSecond(callback: () => Unit) {
while (true) { callback(); Thread sleep 1000 }
}

def timeFlies() {
println("time flies like an arrow...")
}

def main(args: Array[String]) {
oncePerSecond(timeFlies)
}
}


with functions as object you can very simple code a callback.





timeFlies() our callback function.
callback: () => Unit parameter for a function. ()=>Unit is the type of all functions which take no arguments and return nothing.
Thread sleep 1000 is similar to Thread.sleep(1000)


rather the function timeFlies() you can use anonymous functions ala:

oncePerSecond(() => println("time flies like an arrow..."))

"() => code" declare an anonymous function



Clases:


class Complex(real: Double, imaginary: Double) {
def re() = real
def im() = imaginary
}


define class Complex with two arguments,
def re() and im() are getters. return type of these two methods is not given explicitly


object ComplexNumbers {
def main(args: Array[String]) {
val c = new Complex(1.2, 3.4)
println("imaginary part: " + c.im())
}
}


if you have no arguments in function, write: def re = real


class Complex(real: Double, imaginary: Double) {
def re = real
def im = imaginary
override def toString() =
"" + re + (if (im < 0) "" else "+") + im + "i"
}


class Complex(real: Double, imaginary: Double) -> primary constructor, which is part of the class declaration
override -> for overriding functions

(if (im < 0) "" else "+") have you see it ;)




class Rational(numerator: Int, denominator: Int) {

require(denominator != 0)

private val gcd = greatestCommonDivisor(numerator.abs,
denominator.abs)
val n = numerator / gcd
val d = denominator / gcd

def this(n: Int) = this(n, 1)

private def greatestCommonDivisor(a: Int, b: Int): Int =
if (b == 0) a else greatestCommonDivisor(b, a % b)

def + (that: Rational): Rational =
new Rational(n * that.d + d * that.n, d * that.d)

def - (that: Rational): Rational =
new Rational(n * that.d - d * that.n, d * that.d)

def * (that: Rational): Rational =
new Rational(n * that.n, d * that.d)

def / (that: Rational): Rational =
new Rational(n * that.d, d * that.n)

override def toString = n + "/" + d
}



require(denominator != 0) -> look that variable is not null, throw exception


def this(n: Int) = this(n, 1) -> create from Rational(2) -> Rational(2,1)

you can see +-*/ are objects functions, which can be simple overrided

2 Kommentare:

  1. Java Platform, Enterprise Edition (Java EE) is the industry-standard platform for building enterprise-class applications coded in the Java programming language by software development company. The most efficient open source products are used to save the Java software development time and cost keeping up the high quality work. Custom software development is a type of software that is developed either for a specific company or business entity. Small business or large enterprise, our java software development company offers proficiency and capability in all aspects of your Java custom software development project. Java enterprise application development services designed to help businesses. Java Enterprise software development succeed because stable Java standards help developers create multilevel applications with a component based approach. As a Java Enterprise web development outsourcing partner Tenax Technologies assures latest technologies using Java.

    AntwortenLöschen
  2. This is really nice stuff..great information is shared..too much helpful.Thanks for this post.
    web designing company

    AntwortenLöschen