Skip to content

Add try method in safe throws strawman #11817

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions tests/run/safeThrowsStrawman2.check
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
1
failed
failed
47 changes: 47 additions & 0 deletions tests/run/safeThrowsStrawman2.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import language.experimental.erasedDefinitions

object scalax:
erased class CanThrow[-E <: Exception]

infix type throws[R, +E <: Exception] = CanThrow[E] ?=> R

class Fail extends Exception

def raise[E <: Exception](e: E): Nothing throws E = throw e

private class Result[T]:
var value: T = scala.compiletime.uninitialized

def try1[R, E <: Exception](body: => R throws E): (E => Unit) => R = { c =>
val res = new Result[R]
try
given CanThrow[E] = ???
res.value = body
catch c.asInstanceOf[Throwable => Unit]
res.value
}

extension [R, E <: Exception](t: (E => Unit) => R) def catch1(c: E => Unit) = t(c)

import scalax._

def foo(x: Boolean): Int throws Fail =
if x then 1 else raise(Fail())

def bar(x: Boolean)(using CanThrow[Fail]): Int = foo(x)
def baz: Int throws Exception = foo(false)

@main def Test =
try1 {
println(foo(true))
println(foo(false))
} catch1 {
case ex: Fail =>
println("failed")
}
try1 {
println(baz)
} catch1 {
case ex: Fail =>
println("failed")
}