Category Archives: Scala

Implicit parameters in Scala

Implicit parameters allow us to write code where one or more parameters can be supplied automatically by Scala in a similar way to dependency injection works.

For example, let’s assume we have a Calculator class (below) which we want to supply to functions/methods in our application

class Calculator {
  def add(a : Int, b : Int) = a + b;
  def subtract(a : Int, b : Int) = a - b;
}

In this instance I’m going create the equivalent of a singleton to the class, the val name doesn’t really matter in the code I’m demonstrating as Scala will simply locate the matching type within the MyImplicits object.

object MyImplicits {
  implicit val calculator = new Calculator();
}

To use this singleton instance we simply import the MyImplicits._ into our code. Here’s an example of using such code. Notice how the calls to the add and subtract functions in the main method do not need to supply the implicit parameter. This is supplied by Scala for us.

object Main {

  import MyImplicits._

  def add(implicit c : Calculator) : Unit = {
    println(c.add(1, 2));
  }

  def subtract(a : Int, b : Int)(implicit c : Calculator) : Unit = {
    println(c.subtract(a, b));
  }

  def main(args: Array[String]) : Unit = {

    val i = add
    val s = subtract(10, 2)
  }
}

Of course, using such code means we could supply another instance of the Calculator class to either of the add or subtract methods if we wished or change the code to work with traits and implementations which would obviously allow us to import different implementations of the trait. Here’s the code from above but using a trait for the implicit argument

trait Calc {
  def add(a : Int, b : Int) : Int;
  def subtract(a : Int, b : Int) : Int;
}


class Calculator extends Calc {
  override def add(a : Int, b : Int) = a + b;
  override def subtract(a : Int, b : Int) = a - b;
}

object MyImplicits {
  implicit val calculator = new Calculator();
}

object Main {

  import MyImplicits._

  def add(implicit c : Calc) : Unit = {
    println(c.add(1, 2));
  }

  def subtract(a : Int, b : Int)(implicit c : Calc) : Unit = {
    println(c.subtract(a, b));
  }

  def main(args: Array[String]) : Unit = {

    val i = add;
    val s = subtract(10, 2);
  }
}

Currying functions

Currying is probably better known within functional languages. In it’s simplest form we can view a currying as a way to declare a function and if a user of the function supplies less arguments than expected then a function is returned which takes the remaining arguments.

Let’s look at currying using a functional language such as F# first, as this really shows the usefulness of such a capability. We’ll define an add function which takes three parameters

let add a b c = a + b + c

Now we can write code such as

let r = add 1 2

Note: when we create a new function from our curried function, such as r in above, we can call this a partially applied function.

As you can see, we have not supplied all the arguments and hence r is not an integer but is instead a function which now accepts a single argument, i.e. the final argument the add function expects. Therefore we can write the following code against the returned function

let i = r 3

Now, i is an integer and contains the result of add 1 2 3 function call (i.e. the value 6).

Currying comes “built-in” syntactically in languages such as F#. We can write explicit code to demonstrate what in essence happens when we work within currying capable languages. Here’s an F# example which shows how we create functions returning functions along with closures to pass the preceding function arguments to each inner function

let add a = 
    let add1 b = 
        let add2 c = 
            a + b + c
        add2
    add1

Note: The F# compiler does NOT create the code equivalent to the above when we create functions unless the usage of the add method includes using it in a curried scenario.

The above is written in F# but you’ll notice that this same technique can easily be written in languages such as C#, Java etc. Here’s the same code in a verbose implementation in C#

public static Func<int, Func<int, int>> Add(int a) => 
   new Func<int, Func<int, int>>(b => (c => a + b + c));

Thankfully C# allows a less verbose syntax, so the above can be rewritten as

public static Func<int, Func<int, int>> Add(int a) =>
   b => (c => a + b + c);

To call such a function we’d need to write code such as

var i = Add(1)(2)(3)

This is not as elegant as the F# code (in my opinion) but does allow currying and partially applied functions in C#.

As you’d expect – another functional language, Scala, supports currying using the following syntax

def add(a : Int)(b : Int)(c : Int) = a + b + c;

val r = add(1)(2)_
// or alternate syntax
// val r = add(1)(2)(_)
val i = r(3)

Notice that we require the _ (underscore) to ignore the third argument and we need to wrap each argument within brackets (creating parameter groups) to enable the function to be curried. The missing last argument need now be enclosed within brackets.

Scala also allows us to create partially applied functions where it’s not just the last n parameters that make up the new function. For example (let’s change the argument types to a string to the output is more obvious.

def mid(a : String)(b : String)(c : String) = a + b + c;

def m = mid("Start ")(_:String)(" End")
println(m("Hello World"))
// outputs Start Hello World End

In this case we’re making a partially applied function using the curried function mid where in usage we miss out the middle parameter in the example usage. However we must also supply the type along with the _ placeholder.

Writing our Play application from scratch

There’s no doubt it’s much better to use a template or in this case a seed (as outlined in my previous post Starting out with the Playframework (in IntelliJ)) set of code to get us up and running with any application, but I like to know what’s going on with my code, I’m not mad on just leaving it as “magic happens”.

So here’s me, reverse engineering the Play seed and creating my own code from scratch. You should be able to work through each step and at the end, you’ll end up with a single page “Hello World” app.

Lets get all the bits in place…

Creating the Project

From IntelliJ

  • Go to File | New Project
  • Select Scala | SBT
  • Name your project
  • Ensure correct Java and Scala versions selected
  • Press Finish

Add support for the Play plugin

Select the project node in the package/project (sources root) treeview and right mouse click on it, select new file and name the file plugins.sbt, place the following into it

addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.5.14")

this will add the Play plugins

Edit the build.sbt

Now open build.sbt and add the following below the scalaVersion line

lazy val root = (project in file(".")).enablePlugins(PlayScala)

libraryDependencies += filters
libraryDependencies += "org.scalatestplus.play" %% "scalatestplus-play" % "2.0.0" % Test

Note: I had to change the scalaVersion to 2.11.11 to get this code to work, obviously it could be a versioning issue on my part, otherwise I got unresolved dependencies.

Click Enable Auto-Import

Add a gradle build file

Add a new file at the same level as the build.sbt and name it build.gradle. Add the following

plugins {
    id 'play'
    id 'idea'
}

task wrapper(type: Wrapper) {
    gradleVersion = '3.1'
}

repositories {
    jcenter()
    maven {
        name "typesafe-maven-release"
        url "https://repo.typesafe.com/typesafe/maven-releases"
    }
    ivy {
        name "typesafe-ivy-release"
        url "https://repo.typesafe.com/typesafe/ivy-releases"
        layout "ivy"
    }
}

def playVersion = '2.5.14'
def scalaVersion = '2.12.2'

model {
    components {
        play {
            platform play: playVersion, scala: scalaVersion, java: '1.8'
            injectedRoutesGenerator = true

            sources {
                twirlTemplates {
                    defaultImports = TwirlImports.SCALA
                }
            }
        }
    }
}

dependencies {
    ['filters-helpers', 'play-logback'].each { playModule ->
        play "com.typesafe.play:${playModule}_$scalaVersion:$playVersion"
    }
}

Configuration folder

Now Add a conf folder at the same level as the project folder (i.e. just select the root, right mouse click, select new directory and name it conf). Select the conf folder, right mouse click and select Mark Directory As… and select Unmark as Resource Root.

Right mouse click on the conf directory, select New File and name it routes (it’s just a text file). Place the following in the file

GET   /   controllers.IndexController.index

Add another file to conf named application.conf. We’re not actually putting anything in this file.

Create the app folder

Now, again at the root level, create another directory named app and Unmark as Source Root. In this directory add a controllers directory and views.

In app, add a new file named Filters.scala and add the following to it

import javax.inject.Inject

import play.api.http.DefaultHttpFilters

import play.filters.csrf.CSRFFilter
import play.filters.headers.SecurityHeadersFilter
import play.filters.hosts.AllowedHostsFilter

class Filters @Inject() (
   csrfFilter: CSRFFilter,
   allowedHostsFilter: AllowedHostsFilter,
   securityHeadersFilter: SecurityHeadersFilter
   ) extends DefaultHttpFilters(
  csrfFilter,
  allowedHostsFilter,
  securityHeadersFilter
)

Add the controllers and views

Okay, before we’ll actually see anything of use we need controllers and views, but in essence at this point you can create a configuration (SBT Task) with the Task run and should be able to run the http server up and see an error as it cannot find the IndexController (at least this gives us the feeling we’re almost there).

Now in the app/controllers folder add a new file named IndexController.scala and place the following code in it

package controllers

import javax.inject._
import play.api._
import play.api.mvc._

@Singleton
class IndexController @Inject() extends Controller {
   def index = Action { implicit request =>
      Ok(views.html.index())
   }
}

and now we need the index view so in app/views add an index.scala.html file and a main.scala.html (this will be our main entry point and the index maps to out IndexController). So the main file should look like this

@(title: String)(content: Html)

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>@title</title>
    </head>
    <body>
@content
    </body>
</html>

and index.scala.html should look like this

@()

@main("Hello World") {
<h1>Hello World</h1>
}

Note: the @main passes Hello World through to main.scala.html and that file creates the equivalent of an input argument @(title: String) and (content: Html) the title is what’s passed from index.scala.html in the @main argument.

Now run up the application and using your browser check http://<ip_address>:9000 and you should see the results of your index.scala.html displayed – “Hello World”.

You might feel a little familiar with the @ commands in the html files – these are template commands which the Play Template Engine provides – they’re similar to the likes of Razor and other templating engines.

So for example we might take the request (passed into our IndexController and inject into out html template like this

def index = Action { implicit request =>
  Ok(views.html.index(name = request.rawQueryString));
}

and in the index.scala.html

@(name: String)

@main("Hello World"){
<h1>Hello @name</h1>
}

Now if we navigate to this http://localhost:9000/?Parrot in our browser, we should see Hello Parrot displayed.

Next steps

Unlike the seed code, I removed all CSS, JavaScript etc. In the seed application off of root we have a public directory with public/images, public/javascripts and public/stylesheet. To make these folders available to our *.scala.html files, we need to add a route to the conf/routes file, for example

GET     /assets/*file               controllers.Assets.versioned(path="/public", file: Asset)

Now, in our *scala.html files we can access these aseets using code such as

@routes.Assets.versioned("javascripts/main.js")"

here’s the seed main.scala.html file to demonstrate including stylesheets, images and scripts

@(title: String)(content: Html)

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>@title</title>
        <link rel="stylesheet" media="screen" href="@routes.Assets.versioned("stylesheets/main.css")">
        <link rel="shortcut icon" type="image/png" href="@routes.Assets.versioned("images/favicon.png")">

    </head>
    <body>
        @content
      <script src="@routes.Assets.versioned("javascripts/main.js")" type="text/javascript"></script>
    </body>
</html>

Logging

Obviously, once we really get going with our code we’ll probably want to start logging interactions. Play comes with a default logger built in which is as simple to use as this

  • import play.api.Logger
  • Logger.debug(“Some String”)

Starting out with the Playframework (in IntelliJ)

Getting a seed application installed

I couldn’t find a “how to” for setting up play from scratch but instead it seems best to download a seed project from the Play Starter Projects.

Select the Play Scala Starter Example and download it – unzip to a folder and now you have a bare bones play application.

Importing the seed application into IntelliJ

  • From File, select New Project
  • Select Scala then SBT
  • Now select the folder where your seed project is
  • Build the project

If you get this error message object index is not a member of package views.html then Select View | Tools Windows | Terminal (or Alt+F12) and a terminal window will open, now run the following

  • sbt clean
  • sbt compile

See this post on this problem “object index is not a member of package views.html” when opening scala play project in scala ide”.

Cleaning then compiling seemed to work for me.

Creating a Run configuration

You may find that if you click Run, the only option is “All in root” and from this you might find IntelliJ tries to run some tests.

We need to create a new configuration to run play via sbt.

See Setting up your preferred IDE, steps recreated from this post below.

  • Select Run | Edit Configuration
  • Press the + button
  • Select SBT Task
  • Name you’re task – mine’s Run Play, simple enough
  • In the Tasks edit box type run
  • Press OK

Now when you want to run the application use this configuration and sbt run will get executed. Now you can go to http://locahost:9000 and see your running app.
Play Tutorials

Scala classes/objects/traits a little more in depth

Recap on what a class, object and trait are…

A class is analogous to a C# class which is created on a per instance bases. An object is a singleton, analogous to a static class in C# and a trait can how declarations of functions (without implementations) or include implementations which is analogous to a C# abstract class.

So in summary

ScalaC#
classclass
objectstatic class
traitabstract class

Class

As previously mentioned, a class is a type which we can create an instance of, and cannot have abstract (or non-implemented) functions (see trait for abstract/interface types)

class Rectangle(width: Int, height: Int) {
  def area = width * height
}

and we can extend/derive from this using the extend keyword, giving us

class Square(side: Int) extends Rectangle(side, side) {
}

Object

As previously stated, an object can be viewed as a static class (in C#), giving us

object ShapeFactory {
  def createSquare(side: Int) = 
     new Square(side)
  def createRectangle(width: Int, height: Int) = 
     new Rectangle(width, height)
}

In use, we do not need to use the new keyword (just like C#), so we can use this factory like this

val square = ShapeFactory.createSquare(5)
assert(square.area == 25)

Trait

A trait can be viewed as being analogous to an abstract class. We can have functions with implementations or no implementation so that any class which extends this trait must implement the unimplemented functions. Here’s a trait with a single abstract function (no implementation) named area and an implementation of a function named name

trait Shape {
  def area : Int
  
  def name = "Shape"
}

We cannot create a trait without implementing the area function, but this doesn’t mean we must create a class (as such), we can create what C# might call and anonymous type, for example

val s = new Shape {
   override def area: Int = 20
}

But ofcourse, we can also extend the trait with another trait or a concrete implementation as a class, for example

class Rectangle(width: Int, height: Int) extends Shape {
  def area = width * height
}

Functions, by default, are virtual (as per Java) and so we can override the name function, for example

class Rectangle(width: Int, height: Int) extends Shape{
  def area = width * height

  override def name: String = "Rectangle"
}

If we want to stop a function being overridden we can use the final keyword (again like java). So Shape might be defined as

trait Shape {
  def area : Int

  final def name = "Shape"
}

Trait as an interface

So one thing you might notice is that in C# and Java we have the concept of an interface. Scala doesn’t support a specific interface keyword. So in this way it’s similar to C++ in that we can simply use a trait without any implementations.

For example

trait Shape {
   def area : Int
}

We can extend traits, for example

trait Triangle extends Shape {
  def isRightAngle : Boolean
}

and ofcourse we could have implemented some functions within the extended type. To implement a class from a Triangle we can just write the following

class RightAngleTriangle(adjacent: Int, opposite: Int) extends Triangle {
  override def area: Int = (adjacent * opposite) / 2
  override def isRightAngle: Boolean = true
}

How to create property like functionality in Scala

Scala has a slightly strange syntax for the equivalent of C# properties. Let’s take a look

class Person(private var _name: String) {
  // getter
  def name = _name
  // setter
  def name_=(m: Int): Unit = {
    println("Setter called")
    _name = m
  }
}

// code to call the above
val c = new Person("Scooby Doo")
c.name = "Scrappy Doo"

In the Person constructor we mark the _name as private so it cannot be altered outside of the class and notice it’s marked as a var as its used as the backing field for the name property. The getter name is pretty standard but the name_= is a little stranger.

Note: There can be no space between the _ and =

This is the syntax for a setter, you do not need to use something like c.name_= “Name” it simply translates to c.Name = “Name”.

Learning Scala – day 2

In my first post on learning Scala I mentioned using ScalaTest. I’m going to walk through the steps (using IntelliJ community edition) to get up and running with ScalaTest as it’s a great way to try things out (ofourse you could alternatively use the Scala console).

  • Create a new project
  • Select Scala and SBT
  • Give the project a name, mine’s named Demo
  • If not already selected, select the JDK you want to support as well as the SBT and Scala version, or stick with the defaults if they’re already setup correctly

Upon finishing the new project wizard, you’ll get a standard layout of folders, as follows

src/main/scala
src/test/scala

In the root of the project you’ll get a build.sbt file. This is the Scala build system. If we open it, IntelliJ has supplied the bare minimum

name := "Demo"
version := "1.0"
scalaVersion := "2.12.1"

Before we do anything more let’s go into src/main/scala, right mouse click on the folder and select New Scala class. Give it the name Calculator, here’s the code

class Calculator {
  def add(a: Int, b: Int) = {
    a + b
  }

  def subtract(a: Int, b: Int ) = {
    a - b
  }
}

Now, go back to the build.sbt file and add the following

libraryDependencies += "org.scalactic" %% "scalactic" % "3.0.1"

When the build.sbt file was changed you’ll see it asking you to Refresh the Project, Enable auto-import or Ignore. I clicked Enable auto-import.

This will then import more Extendal Libraries (if you want to see what was imported, expand the External Libraries in the project view alt+1, if not already displayed)

Now, we could have done this in one step (but I wanted to demonstrate how the external libraries get added to), but now add the following

libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.1" % "test"

further external libraries will get imported if you refresh (or if auto-import is enabled, after a moment). These now include scalatest.

We’re going to let IntelliJ create our initial unit test fixture. To ensure everything is in place, carry out the following steps

  • Press the Project Structure button or File | Project Structure
  • In the Dependency tab or your project (i.e. mine’s demo) check the scalatest project has has been imported or add your preferred test package here
  • Press OK to close the dialog (or if no changes were made then Cancel is ofcourse fine)

Or if you’re happy all is ready then…

  • Load Calculator.scala into the editor
  • On the line of the class either right mouse click and select Goto | Test or the hot keys ctrl+shift+t
  • You should see a Create New Test popup
  • Select this to display a dialog
  • Now select the functions you want to create tests for, then press OK.

You’ll now be placed into the newly added CalculatorTest class and it’ll look like this

import org.scalatest.FunSuite

class CalculatorTest extends FunSuite {

  test("testAdd") {
  }

  test("testSubtract") {
  }
}

From here we can write our test code and further tests.

Like other test frameworks we now have access to assert functions, so for example we can have the testAdd look like this

test("testAdd") {
   val calc = new Calculator
    
    assert(calc.add(1, 2) == 3)
  }

org.scalatest contains a whole bunch of assert functions that we can use in our tests.

ScalaTest is not the only scala based test library

References

Working with Scala Tests
ScalaTest

Learning Scala – day 1

I’ve decided to learn (at least the basics) of Scala. This post will cover the standard programming constructs and features, whilst not intended to be in depth, it will act as an entry into using Scala or a reminder for myself.

Note: I will be writing this post as somebody who comes from a C# background and has also used F#. So, sorry if you’re reading this and thinking “I don’t know what F# would look like” for example.

val and var

A val is immutable whereas a var is not. Hence assuming we have the following

object Calculator {
  def add(a: Int, b: Int): Int = {
      a + b
  }

  def subtract(a: Int, b: Int): Int = {
    a - b
  }
}

The we can assign our val thus

val calc = Calculator

// this line will error
calc = Calculator

whereas our var will allow reassignment, hence

var calc = Calculator

// this line will success
calc = Calculator

Simple enough.

Types

I’m not going to list all the types supported in Scala – ofcourse we have Int, String etc. What I will say though, is like F#, a type may be inferred or we might specify the type where a hint is required

Let’s see how we can use a type

val inferredString = "Hello"
val explcitString : String = "Hello"

We declare a type after the name of the val/var, as per the example above.

There’s an ultimate base type in Scala (a little like object in C#) and this is called Any. According to Unified Type System this Any type is not the same as the java.lang.Object. In Scala we have AnyRef which IS analogous to java.lang.Object whereas AnyVal is the equivalent base of value types. Ofcourse Any is the base of both AnyValue and AnyRef.

Like F#, Scala prefers the idea of a Nothing value than a null but (again like F#) null is also supported.

Scala, ofcourse, supports collections and arrays.

We can declare and array with type expected type or inferred, for example, these two arrays create the same type of array

// explicit
val a = Array[String]("a", "b")
// inferred
val b = Array("a", "b")

To access/alter an array at a given index we again use brackets (), i.e.

val a = Array("a", "b")
// amend "b" to "c"
a(1) = "c"

Return values

When a method returns a value we can use the return function, for example

def result : Int = {
   return(123)
}

or without parenthesis, i.e. return 123 or, like F# the return can also be the last line of the function, i.e.

def result : Int = {
   123
}

and with the type being inferred we can reduce this further to

def result = {
   123
}

Loops

The for loop, using the to function, for example

for(i <- 1 to 3) {
   print(i);
}

// will print
// 123

The for loop, using the until method

for(i <- 1 until 3) {
   print(i);
}

// will print
// 12

to and until are methods, hence we could use the following syntax

for(i <- 1 to 3) {}
for(i <- 1 to.(3)) {}
for(i <- 1.to(3)) {}

each of the above does the same thing, just with different syntax. What each of these methods does is return a Range, for example, in the the following code r is of type Range

val r = 1.to(3)

for(i <- r) {
   print(i)
}

It’s always worth noting the i is a val (hence immutable) type and is created each time through the loop.

Note: So how can “to” and “until” be used without parenthesis? If a method is zero or one arguments, we do not need the parenthesis. Therefore, if we have code like this

object Calculator {
  def inc(a : Int): Int = {
    a + 1
  }
}

// we can do this

val calc = Calculator
val r = calc inc 2

Back to loops, so we have a for loop, we’ve also got while loops so

var i = 0
while(i < 3) {
   print(i)
   i = i + 1
}

as well as do…while

var i = 0
do {
   print(i)
   i = i + 1
} while(i < 3)

like C#/Java we can also break out of a loop, however this keyword is not part of Scala. To use, we need to import the functionality using

import scala.util.control._

var i = 0
while(true) {
   print(i)
   i = i + 1
   if(i == 3)
      Breaks.break
}

Importing functionality/libraries

As you’ve seen with the Breaks.break method, we can import functionality as we do in C# with using and import in Java, like this

import scala.util.control._

The use of the _ is like a saying import everything within the scala.util.control namespace and we’ll then use code like Breaks.break to call the method, but we could also be more explicit and change our code to be like this

import scala.util.control.Breaks.break

// other code
if(i == 3)
   break

Like F# being built atop .NET and therefore allowing us access to a rich framework and eco-system, Scala is built upon Java and hence allows us access to it’s rich set of frameworks etc.

import java.util.Date

def output  = print(new Date() + ":" + msg)

in the above, it’s probably obvious, we’re using the Java Date class, we can import multiple specific classes like this

import java.util.{Date, Locale}

or for all (as already seen)

import java.util._

Classes and Objects

We can define a class as follows

class Report(msg: String) {

  def output = println(msg)
}

By default (i.e. without an scope declaration) classes are public, we could prefix the class thus private class Report to change from the default.

The msg: String is like a constructor (a similar design came up for Primary constructors in C# 6) but we can also create overload for the constructor like this

class Report(msg: String) {

  def this(msg: String, num: Int) = this(msg + "  " + num.toString)
  def this(num: Int, msg: String) = this(msg + "  " + num.toString)

  def output = println(msg)
}

We can also define an object like this

object Report {

  def output(msg: String) = println(msg)
}

In scala this is known as a singleton object, I would say similar to a static class in C#. Hence does not have a constructor as we cannot create an instance of Report and we do not use the new keyword to use it, i.e.

val s = Report
s.output("Hi")

It’s also possible to associate an object with a class, for example

class Report(msg: String) {

  def this(msg: String, num: Int) = this(msg + "  " + num.toString)
  def this(num: Int, msg: String) = this(msg + "  " + num.toString)

  def output  = Report output(this.msg)
}

object Report {
  def output(msg: String) = println(msg)
}

This pairing of class with an object is known as a companion class and vice versa we can think of the object as the companion object. In the example above, we’ve defined the equivalent of a static method in the object and the class output calls this. Obviously this is a slightly convoluted example, but another use is that the object might include (for example) private fields which are used from the class, like this

class Report(msg: String) {

  def this(msg: String, num: Int) = this(msg + "  " + num.toString)
  def this(num: Int, msg: String) = this(msg + "  " + num.toString)

  def output  = print(Report.name + ":" + msg)
}

object Report {
  private def name = "Report"
}

alternatively, we can import the object and remove the need to prefix use of name with Report – like this

class Report(msg: String) {

  import Report._

  def this(msg: String, num: Int) = this(msg + "  " + num.toString)
  def this(num: Int, msg: String) = this(msg + "  " + num.toString)

  def output  = print(name + ":" + msg)
}

object Report {
  private def name = "Report"
}

Commenting code

As you’ve seen in some of the examples, scala supports // for single line comments as well as the standard (at least in C style languages) /* */

We can also support scaladoc comments, these use /** */ for example

/**
This is a report
*/
class Report(msg: String) {
}

In Intelli> (for example) selecting the Report when used in our code and pressing ctrl+q will result in a popup which will display the documentation for the class, the text with /** */ will be displayed as documentation.

Whoa, hold on, how about an application

So for all of the above, I’ve talked about the language, for these examples I’ve used ScalaTest but what about an entry point for an application.

Ofcourse we have main and we can create our application object like this

object MyApp {
  def main(args: Array[String]): Unit = {
     println("Hello World")
   }
}

As you’ll recall from the section on classes and objects, this is similar to a singleton class with, what we might view as, a static method.

This requires the args : Array[String]) and must return a void/Unit