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.

}<br />

}<br />

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

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

C:/>scala Test<br />

a.getOrElse(0): 5<br />

b.getOrElse(10): 10<br />

C:/><br />

Using isEmpty() Method:<br />

Following is the example of showing how to use isEmpty() to check if the option is None or not:<br />

object Test {<br />

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

val a:Option[Int] = Some(5)<br />

val b:Option[Int] = None<br />

}<br />

}<br />

println("a.isEmpty: " + a.isEmpty )<br />

println("b.isEmpty: " + b.isEmpty )<br />

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

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

C:/>scala Test<br />

a.isEmpty: false<br />

b.isEmpty: true<br />

C:/><br />

<strong>Scala</strong> Option Methods:<br />

Following are the important methods which you can use while playing with Options. For a complete list of methods<br />

available, please check official documentation of <strong>Scala</strong>.<br />

SN Methods with Description<br />

1<br />

2<br />

3<br />

4<br />

5<br />

def get: A<br />

Returns the option's value.<br />

def isEmpty: Boolean<br />

Returns true if the option is None, false otherwise.<br />

def productArity: Int<br />

The size of this product. For a product A(x_1, ..., x_k), returns k<br />

def productElement(n: Int): Any<br />

The nth element of this product, 0-based. In other words, for a product A(x_1, ..., x_k), returns x_(n+1) where 0 < n <<br />

k.<br />

def exists(p: (A) => Boolean): Boolean<br />

Returns true if this option is nonempty and the predicate p returns true when applied to this Option's value.<br />

Otherwise, returns false.<br />

TUTORIALS POINT<br />

Simply Easy Learning

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

Saved successfully!

Ooh no, something went wrong!