lunduniversity.lu.se

Computer Science

Faculty of Engineering, LTH

Denna sida på svenska This page in English

Some code examples to play with

Hello world

Put this in a file called hello.scala:

object helloWorld {

  def main(args: Array[String]) {

    println("Hello, world!")

  }

}

compile with:
> scalac hello.scala

run with:    
> scala helloWorld

 

Put this in a file called myapp.scala:

object helloArgs extends App {

    println("Hello args: " + args.mkString(", ") )

}

compile with:
> scalac myapp.scala

run with:    
> scala helloArgs hejsan svejsan

...Or skip the compilation and just type this in a REPL or in Kojo:

 

println("Hello, world!")

 

Scripting example: Speed Test

  • You can run scala code as a script from the command line and access arguments without pre-compilation.

Run this example speedtestscript.scala from the commandline like this:

> scala speedtestscript.scala 5000
*** Counting from 1 to ... 5000 *** READY!
It took 8.5 milliseconds.

  • You can also run a script in Kojo. Copy and paste the file speedtest.kojo into the Kojo script editor and press the play button.
  • You can also run a script inside the REPL, either by loading the file speedtest.scala using :load

> scala

scala> :load speedtest.scala
Loading speedtest.scala...
sysTime: scala.math.BigDecimal
speedTest: (n: BigInt)Unitscala

> speedTest(5000)
*** Counting from 1 to ... 5000 *** READY!
It took 10 milliseconds.

scala>

  • You can also just paste copied code directly into the REPL using :paste

scala> :paste
// Entering paste mode (ctrl-D to finish)

 

Extensions that feel like part of the language

  • swedish-turtle-graphics-example-ring.kojo
    • Open this file in Kojo and make sure to change language in the Language menu to Swedish before pressing the play button. This code uses abilities in Scala to construct new control structures; a block can be passed to a function with a by-name parameters and parameters can be separated into several parameter lists (so called "currying" of functions).
    • Download a cheat sheet in pdf for the Swedish turtle and its English translation.
    • The Swedish turtle is used at LTH Science center to make it easier to get started with programming for Swedish-speaking kids that have not yet learned enough English.
    • If you go to the ..Kojo/kojo/initk/sv in your Kojo installation folder you can see how the Swedish turtle is defined (you can skip the code completion XML stuff at the end of the file...).
  • repeat-upprepa.scala
    • Example of how to create new control structures in Scala using by-name parameters and function literals.

GUI programming

Parallell programming with actors