What is the advantage of using Option.map over Option.isEmpty and Option.get?

I am new to Scala, coming from a Java background, currently confused with best practice considering Option[T].

It seems to me that the use is Option.mapsimply more functional and beautiful, but this is not a good argument to convince other people. Sometimes the isEmpty check looks more straightforward, so it is more readable. Are there any objective advantages, or are these just personal preferences?

Example:

Option 1:

someOption.map{ value => 
  {
    //some lines of code
  }
} orElse(foo)

Option 2:

if(someOption.isEmpty){
  foo
} else{
  val value = someOption.get
  //some lines of code
}

fold . Option , isEmpty , IMHO. , , , .

+4
3

isEmpty , IMHO

isEmpty, isEmpty/isDefined . . ; . get , isDefined :

if(someOption.isEmpty){
  val value = someOption.get
  //some lines of code
} else{
  //some other lines
}

, , "".

(map ) , get , : ​​. - . , ( ). -, , ; map ... getOrElse fold , .

+2

- , ?

, . , .

, Scala, - . "" Option[T], Future[T], Try[T], Either[A, B] ( . Monad Transformers).

, Option[T] . , , Option[Int], , , return -1. :

val option: Option[Int] = generateOptionValue

var res: Int = if (option.isDefined) {
  val value = option.get
  if (value > 40) value * 2 else -1
} else -1

Option, :

val result: Int = option
  .filter(_ > 40)
  .map(_ * 2)
  .getOrElse(-1)

. , , . , . , , .

try-catch:

var result: String = _
try {
  val maybeResult = dangerousMethod()
  if (maybeResult.isDefined) {
    result = queryDatabase(maybeResult.get)
  } else result = ""
}
catch {
  case NonFatal(e) => result = ""
}

scala.util.Try Option[String] :

val result: String = Try(dangerousMethod())
  .toOption
  .flatten
  .map(queryDatabase)
  .getOrElse("")

, , . Option[T].map, Option[T].get .

, , . , , , , . , , , , , , .

+5

Option, Future. Future.

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Promise
import scala.util.{Success, Try}

// create a promise which we will complete after sometime
val promise = Promise[String]();

// Now lets consider the future contained in this promise
val future = promise.future;

val byGet = if (!future.value.isEmpty) {
  val valTry = future.value.get
  valTry match {
    case Success(v) => v + " :: Added"
    case _ => "DEFAULT :: Added"
  }
}  else "DEFAULT :: Added"

val byMap = future.map(s => s + " :: Added")

// promise was completed now
promise.complete(Try("PROMISE"))


//Now lets print both values

println(byGet)
// DEFAULT :: Added

println(byMap)
// Success(PROMISE :: Added)
+1

Source: https://habr.com/ru/post/1651046/


All Articles