scala
-
OptionTscala/cats2 2023. 1. 16. 10:34
cats OptionT example import cats.data._ import cats.syntax.all._ import scala.util.{Success, Try} object OptionTExample { def main(args: Array[String]): Unit = { val a: Try[Option[Int]] = Success(1.some) val b: Try[Int] = Success(2) val c: Option[Int] = 3.some val d: OptionT[Try, Int] = OptionT.some(4) // OptionT[Try].some(4), OptionT.some is an alias for OptionT.pure val e: OptionT[Try, Int] = ..
-
Nestedscala/cats2 2023. 1. 16. 10:07
cats Nested 예제 import cats.data._ import cats.syntax.all._ import scala.util.{Success, Try} object NestedExample { def main(args: Array[String]): Unit = { val someValue: Try[Option[Int]] = Success(2.some) val basicScala: Try[Option[Int]] = someValue.map(_.map(_ * 3)) val catsScala: Try[Option[Int]] = Nested(someValue).map(_ * 3).value } }
-
Statescala/cats2 2023. 1. 10. 09:49
문제 https://wefree.tistory.com/44 의 문제를 cats State Monad 를 이용해 구현해 본다. 코드 import cats._ import cats.data._ import cats.syntax.all._ object GolfState { def swing(n: Int): State[Int, Int] = State(s => (s+n, s+n)) def main(args: Array[String]): Unit = { val states: Seq[State[Int, Int]] = List(swing(20), swing(10), swing(15)) val finalState: State[Int, Int] = states.reduce(_ *> _) val (s,a) = finalSt..
-
Scala Usingscala/basic 2022. 12. 19. 00:03
scala 2.13 버전부터 scala.util.Using 이 추가되었다. cats-effect 의 Resource 또는 zio 의 Scope 처럼 resource 관리를 위해 사용될 수 있다. AutoCloseable Resource 에서 사용 기본적으로 Using.resource(..) 혹은 Using.resources(..) 를 이용하자. (필요하면 Try 로 감싼다) https://www.scala-lang.org/api/2.13.6/scala/util/Using$$Releasable.html 을 보면 아래와 같은 내용이 있다. An instance of Releasable is needed in order to automatically manage a resource with Using. An ..
-
airframe-di: Dependency Injectionscala/airframe 2022. 11. 19. 22:42
airframe-di 를 이용한 Dependency Injection maven repo: https://mvnrepository.com/artifact/org.wvlet.airframe/airframe 아래정도 기능만 사용하는 것이 좋을 것 같다. https://wvlet.org/airframe/docs/airframe-di#child-sessions 등을 사용하면 테스트나 코드 읽기가 힘들어질 것 같다. Note: +(add) operator 로 design 을 합치거나 override(lazy) 할 수 있다. lazy 하게 적용되기 때문에, 필요한 components 를 나중에 +(add) operator 로 제공되어도 괜찮다. bind[T].toProvider(...) 이것 덕분에 복잡할 수 있는..
-
Scala Closurescala/basic 2022. 10. 21. 19:56
코드 object ScalaApp { def runner(f: () => Int): Unit = { val out = f() println(out) } def sum(x: Int, y: Int): () => Int = { val inner = () => x + y inner } def main(args: Array[String]): Unit = { val f = sum(1, 2) runner(f) } } 설명 python 의 Closure 와 비교해 보자
-
java callback 을 scala Future 로 바꾸기scala/basic 2022. 7. 16. 18:57
문제 다음과 같이 java Async Http Client 의 callback 을 scala Future 로 변경해 코딩해 보자 val asyncHttpClient = org.asynchttpclient.Dsl.asyncHttpClient() val listenableFuture = asyncHttpClient.prepareGet("https://api.agify.io/?name=meelad").execute() val listener = new Runnable { override def run(): Unit = { val body: String = listenableFuture.get().getResponseBody(scala.io.Codec.UTF8.charSet) println(body) } } l..