惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
D
Docker
Microsoft Security Blog
Microsoft Security Blog
Google DeepMind News
Google DeepMind News
M
MIT News - Artificial intelligence
P
Proofpoint News Feed
Engineering at Meta
Engineering at Meta
Y
Y Combinator Blog
Vercel News
Vercel News
F
Fortinet All Blogs
B
Blog
Recent Announcements
Recent Announcements
A
About on SuperTechFans
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - Franky
MongoDB | Blog
MongoDB | Blog
Stack Overflow Blog
Stack Overflow Blog
B
Blog RSS Feed
C
Check Point Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
V
Visual Studio Blog
月光博客
月光博客

博客园 - evilyzou

scala 的List foldLeft用法 Circumflex Scala中的一些特殊字符用法 Scala中的PartialFunction在Lift当中的NamedPF应用 Lift当中的AnyVarTrati源码解析 scala的DynamicVariable用法 SBT和IDEA 开发scala web程序 使用Sbt(一) scalatra web框架安装指南 ASP.NET MVC: Do You Know Where Your TempData Is? 使用IntelliJ IDEA, Maven and the jetty plugin调试web应用程序 Scala GraphViz DOT Parser Scala Standard library Scala 一些基本的语法 Scala 相关的资源和Blog Lift2.0发布 Linux 汇编语言开发指南 Linux2.6内核启动流程学习 [导入]C#强化系列文章五:动态代码的使用(反射和动态生成类) [导入]C#强化系列文章七:序列化和反序列化
Scala中的Either的两个子类(Left,Right)的简单用法
evilyzou · 2010-09-05 · via 博客园 - evilyzou

Scala中有Left,Right两个类,继承于Either,主要用途是表示两个可能不同的类型(它们之间没有交集),Left主要是表示Failure,Right表示有,跟Some类型有点类似,看下下面的代码:

def throwableToLeft[T](block: => T): Either[java.lang.Throwable, T] = 
  try { 
    Right(block) 
  } catch { 
    case ex => Left(ex) 
  } 

大概意思是发生异常就使用pattern matching返回异常

具体使用:

var s = "hello" 
throwableToLeft { s.toUpperCase } match { 
  case Right(s) => println(s) 
  case Left(e) => e.printStackTrace 
} 
// prints "HELLO" 
 
s = null 
throwableToLeft { s.toUpperCase } match { 
  case Right(s) => println(s) 
  case Left(e) => e.printStackTrace 
} 
// prints NullPointerException stack trace