-2

Possible Duplicate:
Why Option[T] ?

i have a problem in my project

how do I retrieve data from the value: [some (test)] and only take the value of (test) only. and using the get method?

or

how do i change the form of value: [some (test)] to "test" just

Community
  • 1
  • 1
Fikrizal
  • 5
  • 1
  • 4
    This question is very confusing. Please see other questions about `Option` and, if you still have questions, try to be more clear. – Daniel C. Sobral Aug 10 '12 at 21:06

1 Answers1

3

Basically, don't use get() ever. There's no situation in which it is a better choice than the alternatives. Option is a way of indicating in the type system that a function might not return what you want. You might think of it as a collection containing 0 or 1 things.

Take a look at the API docs which show several different ways to handle Option; as a collection using map/flatMap, getOrElse, for comprehensions, and pattern matching.

e.g. map:

val maybeData : Option[String] = Some("test")  // or None
val maybeResult = maybeData.map(x : String => doSomethingWithAString(x))

If maybeData is None, nothing happens. If it is Some() you will get back an Option containing the result of doSomethingWithAString(). Note that this will be Option[B] where B is the return type of doSomethingWithAString.

e.g. getOrElse:

val maybeData : Option[String] = Some("test")  // or None
val result : String = maybeData.getOrElse("N/A")

If data is Some, result is "test", otherwise it is "N/A".

e.g. pattern matching:

val maybeData : Option[String] = Some("test")  // or None
val result : String = maybeData match {
  case Some(x) => doSomethingWithAString(x)
  case None => "N/A"
}

You get the picture (note this assumes doSomethingWithAString returns String).

If you use get() and maybeData is None, you get the joy of handling the equivalent of nullpointers. Nobody wants that.

Brian Smith
  • 3,383
  • 30
  • 41