Skip to content

Commit 8a1f569

Browse files
committed
Add try method in safe throws strawman
1 parent a081a74 commit 8a1f569

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

tests/run/safeThrowsStrawman2.check

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
1
2+
failed
3+
failed

tests/run/safeThrowsStrawman2.scala

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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+
import scalax._
13+
14+
def foo(x: Boolean): Int throws Fail =
15+
if x then 1 else raise(Fail())
16+
17+
def bar(x: Boolean)(using CanThrow[Fail]): Int = foo(x)
18+
def baz: Int throws Exception = foo(false)
19+
20+
class Result[T]:
21+
var value: T = scala.compiletime.uninitialized
22+
23+
def try1[R, E <: Exception](body: => R throws E): (E => Unit) => R = { c =>
24+
val res = new Result[R]
25+
try
26+
given CanThrow[E] = ???
27+
res.value = body
28+
catch c.asInstanceOf[Throwable => Unit]
29+
res.value
30+
}
31+
32+
extension [R, E <: Exception](t: (E => Unit) => R) def catch1(c: E => Unit) = t(c)
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+
}

0 commit comments

Comments
 (0)