Scala and Java options, if any, if they don't do something else

Parameters in scala and java are what I struggle with in order to understand and work. I understand it there to eliminate the "zero" processing of hell. Honestly, I think he introduces a different kind of hell!

The way I handle nulls in java is to do something like:

String test = null;
if(test==null) // do something
else  // do something else

Such a solution is what I am trying to do when I switch to parameters.

But in the Option class, there is no method in the scala and java method to say that if null does something, otherwise do something else.

There is a way to set the default value if the object is null, for example

//in scala
test.getOrElse("defaulted")

I was wondering why there cannot be methods like the implicit class that I wrote for the “pimping” of the scala option

object Definitions{
  implicit class OptionExtensions[$Data](option: Option[$Data]){
    def perform (found: ($Data)=>Any, notFound: ()=>Any): Any={
      option match{
        case Some(data)=> found(data)
        case None=> notFound()
      }
    }
  }
}

, . , , :

import Definitions._

val test : Option[String] = None

var builder =new StringBuilder


test.perform(builder ++= _, ()=>addError("not found"))
//or
println(test.perform(_.reverse, ()=>{"something else"}))

def addError(error:String)={
  println(error)
}

. - . , , "", . Option . , ?

+4
2

scala :

  • optValue.map(successFunction).getOrElse(errorFunction)
  • optValue.fold(errorFunction)(successFunction)

, , , fold.

java .map, , .fold,

EDIT: , :

Some(2).fold
  {
    println("error")
  }
  {
    value =>
      println(s"Success: $value")
  }
+5

, , .

( Java) , () , , .

, . , ?

...

, ?

  • , - null,
  • , , , .

, /, , , , , null ( )!).

, , , , , . , null ( ), ! , ?

, , , , , , !; )

+1

All Articles