Hacker News new | ask | show | jobs
by mark242 3351 days ago
In reality my function would rarely exist in the Scala world since having a weakly-typed return like that is cringeworthy to say the least. But it's better to see this in action with Scala options.

  val myOptionalVar: Option[String] = functionThatReturnsOption()

  myOptionalVar match {
    case Some(str) if str.length > 10 => System.out.println("This is a long string.")
    case Some(str) => System.out.println("This is a short string.")
    case None => System.out.println("This code would be fifteen lines of null checking in Java.")
  }
2 comments

With Java 8 having Optional and Lambdas, this is no longer the case:

  final Optional<String> myOptionalVar = functionThatReturnsOptional();
  
  final String output = myOptionalVar
    .map(str -> str.length() > 10
      ? "This is a long string."
      : "This is a short string.")
    .orElse("This code would be fifteen lines of null checking in Java.");
  
  System.out.println(output);
I think this is less-rare than you think. In my Scala code, I have a lot of matching on weakly-typed values which come from parsing JSON objects (where I also deal with a lot of optional values).