Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return optional information from methods?

Tags:

scala

The general question is how to return additional information from methods, beside the actual result of the computation. But I want, that this information can silently be ignored.

Take for example the method dropWhile on Iterator. The returned result is the mutated iterator. But maybe sometimes I might be interested in the number of elements dropped.

In the case of dropWhile, this information could be generated externally by adding an index to the iterator and calculating the number of dropped steps afterwards. But in general this is not possible.

I simple solution is to return a tuple with the actual result and optional information. But then I need to handle the tuple whenever I call the method - even if I'm not interested in the optional information.

So the question is, whether there is some clever way of gathering such optional information?

Maybe through Option[X => Unit] parameters with call-back functions that default to None? Is there something more clever?

like image 454
ziggystar Avatar asked Jun 24 '11 11:06

ziggystar


People also ask

How do you return Optional value?

To return the value of an optional, or a default value if the optional has no value, you can use orElse(other) . Note that I rewrote your code for finding the longest name: you can directly use max(comparator) with a comparator comparing the length of each String.

How do you return an Optional String in Java?

But instead of declaring the field as Optional, you can use the getter method returns the Optional<String> value using Optional. ofNullable(this. firstName).

How do I get Optional strings?

In Java 8, we can use . map(Object::toString) to convert an Optional<String> to a String .

Is return statement Optional in Java?

The Java compiler does a (limited) flow analysis and when it can determine that all flows of control lead to an exception you don't need a return.


2 Answers

Just my two cents here…

You could declare this:

case class RichResult[+A, +B](val result: A, val info: B)

with an implicit conversion to A:

implicit def unwrapRichResult[A, B](richResult: RichResult[A, B]): A = richResult.result

Then:

def someMethod: RichResult[Int, String] = /* ... */

val richRes = someMethod
val res: Int = someMethod
like image 142
Jean-Philippe Pellet Avatar answered Sep 20 '22 04:09

Jean-Philippe Pellet


It's definitely not more clever, but you could just create a method that drops the additional information.

def removeCharWithCount(str: String, x: Char): (String, Int) =
  (str.replace(x.toString, ""), str.count(x ==))

// alias that drops the additional return information
def removeChar(str: String, x: Char): String =
  removeCharWithCount(str, x)._1
like image 40
kassens Avatar answered Sep 19 '22 04:09

kassens