09.10.2014 Views

Download Scala Tutorial (PDF Version) - Tutorials Point

Download Scala Tutorial (PDF Version) - Tutorials Point

Download Scala Tutorial (PDF Version) - Tutorials Point

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Value = 1<br />

C:/><br />

Convert to String:<br />

You can use Tuple.toString() method to concatenate all the elements of the tuple into a string. Following is the<br />

example to show the usage:<br />

object Test {<br />

def main(args: Array[String]) {<br />

val t = new Tuple3(1, "hello", Console)<br />

}<br />

}<br />

println("Concatenated String: " + t.toString() )<br />

When the above code is compiled and executed, it produces the following result:<br />

C:/>scalac Test.scala<br />

C:/>scala Test<br />

Concatenated String: (1,hello,scala.Console$@281acd47)<br />

C:/><br />

Swap the Elements:<br />

You can use Tuple.swap method to swap the elements of a Tuple2. Following is the example to show the usage:<br />

object Test {<br />

def main(args: Array[String]) {<br />

val t = new Tuple2("<strong>Scala</strong>", "hello")<br />

}<br />

}<br />

println("Swapped Tuple: " + t.swap )<br />

When the above code is compiled and executed, it produces the following result:<br />

C:/>scalac Test.scala<br />

C:/>scala Test<br />

Swapped tuple: (hello,<strong>Scala</strong>)<br />

C:/><br />

<strong>Scala</strong> Options<br />

<strong>Scala</strong> Option[T] is a container for zero or one element of a given type. An Option[T] can be<br />

eitherSome[T] or None object, which represents a missing value. For instance, the get method of <strong>Scala</strong>'s Map<br />

produces Some(value) if a value corresponding to a given key has been found, or None if the given key is not<br />

defined in the Map. The Option type is used frequently in <strong>Scala</strong> programs and you can compare this to null value<br />

available in Java which indicate no value. For example, the get method of java.util.HashMap returns either a value<br />

stored in the HashMap, or null if no value was found.<br />

Let's say we have a method that retrieves a record from the database based on a primary key:<br />

def findPerson(key: Int): Option[Person]<br />

TUTORIALS POINT<br />

Simply Easy Learning

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!