File tree Expand file tree Collapse file tree 2 files changed +50
-0
lines changed Expand file tree Collapse file tree 2 files changed +50
-0
lines changed Original file line number Diff line number Diff line change 1+ 1
2+ failed
3+ failed
Original file line number Diff line number Diff line change 1+ import language .experimental .erasedDefinitions
2+
3+ object scalax :
4+ erased class CanThrow [- E <: Exception ]
5+
6+ infix type throws [R , + E <: Exception ] = CanThrow [E ] ?=> R
7+
8+ class Fail extends Exception
9+
10+ def raise [E <: Exception ](e : E ): Nothing throws E = throw e
11+
12+ private class Result [T ]:
13+ var value : T = scala.compiletime.uninitialized
14+
15+ def try1 [R , E <: Exception ](body : => R throws E ): (E => Unit ) => R = { c =>
16+ val res = new Result [R ]
17+ try
18+ given CanThrow [E ] = ???
19+ res.value = body
20+ catch c.asInstanceOf [Throwable => Unit ]
21+ res.value
22+ }
23+
24+ extension [R , E <: Exception ](t : (E => Unit ) => R ) def catch1 (c : E => Unit ) = t(c)
25+
26+ import scalax ._
27+
28+ def foo (x : Boolean ): Int throws Fail =
29+ if x then 1 else raise(Fail ())
30+
31+ def bar (x : Boolean )(using CanThrow [Fail ]): Int = foo(x)
32+ def baz : Int throws Exception = foo(false )
33+
34+ @ main def Test =
35+ try1 {
36+ println(foo(true ))
37+ println(foo(false ))
38+ } catch1 {
39+ case ex : Fail =>
40+ println(" failed" )
41+ }
42+ try1 {
43+ println(baz)
44+ } catch1 {
45+ case ex : Fail =>
46+ println(" failed" )
47+ }
You can’t perform that action at this time.
0 commit comments