카테고리 없음

[자바] 부울에 대한 사후 할당 연산자가 있습니까?

필살기쓰세요 2021. 2. 19. 02:58

No, there's nothing built-in that does what you describe. You'd do it with a temporary variable:

boolean flag = true;
boolean returnValue = flag;
flag = false;
return returnValue;

Or based on your further edit to the question ("The structure looks something like this"), you can use !:

boolean flag = false;
// some operations which can set the flag true
if(flag) return !(flag = false);
// some operations which can set the flag true
if(flag) return !(flag = false);
// some operations which can set the flag true
if(flag) return !(flag = false);

I really, really would not do that. It's unnecessarily obtuse.

-------------------

java.util.concurrent.AtomicBoolean을 살펴보십시오. 나는 이것을 시도하지 않았지만 당신이 묻는 행동을 줄 수 있습니다.

AtomicBoolean flag = new AtomicBoolean(true);
System.out.println("First, I'm " + flag.get());
Boolean was = flag.getAndSet(false);
System.out.println("I was " + was + " but now I'm " +
    Flag.get());
    
-------------------

아니, 그렇게 할 수있는 방법이 없습니다.

왜 안돼?

당신은 자바 언어 디자이너에게 진짜 대답을 물어야 할 것이지만, 나는 그들이 그러한 제안을 손에서 기각했을 것이라고 생각한다. Java는 배우고, 읽고, 이해하기 쉬운 언어로 설계되었습니다 . 간결한 방식으로 "영리한"일을하도록 설계된 연산자를 추가하면 일반 프로그래머 에게 언어를 배우기 어렵고 읽기 어렵게 만들 수 있습니다 . 그리고 연산자가 소수의 사용 사례에서만 실제로 유용하다면 가독성 대 유틸리티 인수를 이기기가 더 어려워집니다.

또한 Java에 새로운 기능을 추가하는 것은 다른 (기존) 언어 기능과의 상호 작용으로 인해 상상하는 것보다 기술적으로 더 어렵습니다.

그리고 실제로 이것을 뒷받침하는 선례가 있습니다. Project Coin의 Java 7/8 개정 제안 중 하나는 Java에 elvis 연산자추가하는 것이 었습니다 . 그 제안은 고려되었고 결국 기각되었습니다 .



출처
https://stackoverflow.com/questions/39940110