0

I presume if I write:

Boolean doIt; ... if (doIt) { doSomething();} 

There is some function in the Boolean class that gets called that returns a boolean that the if statement evaluates to decide to doSomething() or not. What is the name of that function so I can write a class like:

public class MagicBoolean { public boolean toBoolean() { // this is the function name I am looking for return true; } ... MagicBoolean doIt; ... if (doIt) { doSomething(); } // doIt.toBoolean() is implicitly called here 

and get the same effect. And, no I don't want to extend Boolean as the logic in toBoolean will be much more complex than checking a simple value and it may involve computation or it may be a memo-ized value, but I don't want the uses of that "value" to know or care. It's just a flag to tell them that the strategy being used wants them to do this (or that) at this particular time.

7
  • 4
    This is called auto(un)boxing. And your own classes cannot do it. Not without custom code generation/replacement. Commented Nov 9, 2020 at 20:20
  • So, there is no equivalent of operator boolean() like in C++. Commented Nov 9, 2020 at 20:24
  • There is no operator overloading in Java. Commented Nov 9, 2020 at 20:25
  • 1
    I think you need to think a bit more OO and a bit less procedurally. For example a.ifSomething(this::doSomething). Commented Nov 9, 2020 at 20:29
  • 1
    Basically closely to how Optional.ifPresent() works. Commented Nov 9, 2020 at 20:31

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.