Defining a simple Scala method

This is a different take on the Hello, World! example seen elsewhere.

In it we will call a method to get this String and then print it. It should serve as an example of the terse methods we can write in Scala.

object Runner extends App {

  println(greeting)
  
  def greeting = {
    "Hello, World!"
  }
}

Looking at the greeting method we can see how this is much shorter than the equivalent in Java.

Firstly, the method takes no arguments so we don’t declare them.

Secondly, the method doesn’t need to specify the return type – the compiler can see that it returns a String.

Lastly, it doesn’t need a return statement, the last value is returned automatically.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s