콘텐츠로 이동

2024 10 17

2024-10-17

Scala Lazy val

참고: https://www.baeldung.com/scala/lazy-val 참고: https://for-development.tistory.com/141

  • 개요
    • val은 변수 선언시 실행, lazy val은 해당 변수 접근시 실행
    • 컴파일러는 lazy val의 표현을 바로 평가하지 않는다.
      • 첫번째 접근시에 평가! 그러고 저장해둠
  • Scala <-> Java

    • Scala
      class Person {
          lazy val age = 27
      }
      
    • Java
      public class Person {
          private int age;
          private volatile boolean bitmap$0;
      
          private int age$lzycompute() {
              synchronized (this) {
                  if (!this.bitmap$0) {
                      this.age = 27;
                      this.bitmap$0 = true;
                  }
              }
              return this.age;
          }
      
          public int age() {
              return this.bitmap$0 ? this.age : this.age$lzycompute();
          }
      }
      
  • 데드락 주의!
    • 순환 참조마냥 lazy val 걸려있으면 곤란해질 수 있음
      object FirstObj {
        lazy val initialState = 42
        lazy val start = SecondObj.initialState
      }
      
      object SecondObj {
        lazy val initialState = FirstObj.initialState
      }
      
      object Deadlock extends App {
        def run = {
          val result = Future.sequence(Seq(
            Future {
              FirstObj.start
            },
            Future {
              SecondObj.initialState
            }
          ))
          Await.result(result, 10.second)
        }
        run
      }
      

COALESCE

참고: https://velog.io/@gooook/SQL-COALESCE 참고: https://wnwa.tistory.com/35

  • 기본
    • 병합한다는 의미의 함수
  • 사용법
    • SELECT COALESCE(col1, col2, ..., colN) FROM table
    • col1이 NULL이 아니면 col1 반환, NULL이면 col2 반환
      • col2가 NULL이 아니면 col2 반환, NULL이면 col3 반환 ...
    • 표준 SQL 함수
    • 특정열의 NULL값을 적절한 값으로 치환할 때 사용도 가능
      SELECT div, COALESCE(div, 0) FROM table_a;