2023 03 03
2023-03-03
Scala at Light Speed
참고: https://www.youtube.com/watch?v=-8V6bMjThNo&list=PLmtsMNDRU0BxryRX4wiwrTZ661xcp6VPM
Advanced
- Lazy Evaluation
- 실제 사용되는 시점에 초기화 됨
- 앞에
lazy 예약어를 쓴다면 초기화 가능
lazy val aLazyValue = 2
lazy val lazyVal = {
println("I am lazy")
48
}
-
Pseudo-Collections
- [Option]
- 자바의 Optional과 동일
def methodWhichCanReturnNull(): String = "Hello World!"
val anOption = Option(methodWhichCanReturnNull())
val stringProcessing = anOption match {
case Some(string) => s"I have: $string"
case None => "Obtained Nothing"
}
- [Try]
- try를 예외를 발생시킬 수 있는 메서드를 감싸기
def methodWhichCanThrowException(): String = throw new RuntimeException
val aTry = Try(methodWhichCanThrowException())
val anotherStringProcessing = aTry match {
case Success(validValue) => s"I have obtained a valid string: $validValue"
case Failure(ex) => s"I have obtained an exception: $ex"
}
- Async Programming
- Future를 사용해 별도의 쓰레드에서 작업을 돌릴 수 있음
val aFuture = Future({
println(Thread.currentThread().getName) // scala-execution-context-global-11
println("Loading")
Thread.sleep(1000)
println("Value computed!")
50
})
-
Implicit Basics
-
[Implicit Args]
- 은근 슬쩍 디폴트 값을 넣어드립니다
- implicit 두개 있으면
No implicit arguments of type: Int 와 같은 에러가 뜹니당
def aMethodWithImplicitArgs(implicit arg: Int): Int = arg + 1
implicit val myImplicitInt = 46
println(aMethodWithImplicitArgs)
-
[Implicit Conversions]
- 해당 타입으로 수행할 수 없는 행위의 경우, 묵시적 형 변환을 통해 처리할 수 있는지 검사
- 은근슬쩍 바꾸기 때문에 위험해!
implicit class MyRichInteger(n: Int) {
def isEven() = n % 2 == 0
}
println(23.isEven())