scala - Pattern match on Tuple2 of Success -
i have 2 futures of try , want if both of them complete. both futures independent. here code
def a1: future[try[string]] = future { success("a1") } def a2: future[try[int]] = future { success(2) } val r1 = { c1 <- a1 c2 <- a2 } yield (c1, c2) r1.map { case tpl: (success[string], success[int]) => println("success") case _ => println("failure") } this prints success. problem because pattern matching on tuple2, because of erasure if second element failure first case executed. if change a2
def a2: future[try[int]] = future { failure(new internalerror("error")) } and again execute this
val r1 = { c1 <- a1 c2 <- a2 } yield (c1, c2) r1.map { case tpl: (success[string], success[int]) => println("success") case _ => println("failure") } now when a2 returns failure above code still prints success. how fix this? non pretty solution check elements of tuple using isinstanceof[success[string]] , isinstanceof[success[int]] , act on truth values there better?
you can pattern match on tuple content:
r1.map { case (_: success[string], _: success[int]) => println("success") case _ => println("failure") } this way overcomes type erasure calling tuple's unapply method, getting tuple elements , checking types. , tuple elements have runtime types intact either success or failure.
Comments
Post a Comment