TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Uniform Handling of Failure in Switch

20 点作者 lichtenberger超过 1 年前

3 条评论

sixthDot超过 1 年前
That reminds me a problem I thought I had in STYX...<p>For a few months I had the feeling that a good switch-expression requires the bottom type... It turns out that the `assert(0)` idiom, used in a lambda, is sufficient:<p><pre><code> var u32 a = switch b do { 1 =&gt; 2, &#x2F;* ... *&#x2F; else =&gt; function(): u32 =&gt; {assert(0, &quot;crash&quot;);}() }; </code></pre> The `else` case (similar to C `default`) simply crashes the program but the type system is happy because the lambda return type is compatible.
评论 #38732019 未加载
DarkNova6超过 1 年前
I think the transformative potential for error handling in Java cannot be overstated. Effectively, this means exceptions can be handled as errors without polluting the return type with an ever-growing list of error-monads.<p>The following example shows this nicely:<p>&gt; Future&lt;String&gt; f = ...<p>&gt; switch (f.get()) {<p>&gt; case String s -&gt; process(s);<p>&gt; case throws ExecutionException(var underlying) -&gt; throw underlying;<p>&gt; case throws TimeoutException e -&gt; cancel();<p>&gt; }<p>Note that I don&#x27;t get the hate for exceptions. Sometimes, handeling the error somewhere up the callstack is exactly the right solution. The problem was that Java did not have convenient syntax for handeling exceptions at call-site.<p>FYI: There was also an interesting discussion in the Java mailing lists also going into some implementation details regarding the representing bytecode:<p><a href="https:&#x2F;&#x2F;mail.openjdk.org&#x2F;pipermail&#x2F;amber-spec-experts&#x2F;2023-December&#x2F;003959.html" rel="nofollow noreferrer">https:&#x2F;&#x2F;mail.openjdk.org&#x2F;pipermail&#x2F;amber-spec-experts&#x2F;2023-D...</a>
评论 #38732854 未加载
throwat2341超过 1 年前
I really think the `case throws` is brilliant.<p>Next, lets add a `never` type to make this legal.<p><pre><code> var foo = switch (bar) { case String s -&gt; s, case Number n -&gt; return, };</code></pre>