精华帖 (0) :: 良好帖 (1) :: 新手帖 (11) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2009-10-16
alanwu 写道 fineqtbull 写道 scala> def g(): Int = try { 1 } finally { 2 } g: ()Int scala> g() res19: Int = 1 而上述代码就比较“独特”了,与return语句不同,返回的是try中的1。 这个谁能解释一下? 编译成Java代码会是什么样子? 像是这样吧 class U { private static int foo() { int result; try { result = 1; return result; } finally { result = 2; } } public static void main(String[] args) { System.out.println(foo()); } } |
|
返回顶楼 | |
发表时间:2009-10-16
alanwu 写道 fineqtbull 写道 scala> def g(): Int = try { 1 } finally { 2 } g: ()Int scala> g() res19: Int = 1 而上述代码就比较“独特”了,与return语句不同,返回的是try中的1。 这个谁能解释一下? 编译成Java代码会是什么样子? 有意思,我也测一下 def g(): Int = try { 1 } finally { 2 } //return 1 public int g() { int exceptionResult1 = 0; exceptionResult1 = 1; 2; return exceptionResult1; Exception exception; exception; 2; throw exception; } def g(): Int = try { return 1 } finally {return 2 } //return 2 public int g() { int exceptionResult1 = 0; true; return 2; Exception exception; exception; return 2; } def g(): Int = try { return 1 } finally { 2 } //return 1 public int g() { int exceptionResult1 = 0; 2; return 1; Exception exception; exception; 2; throw exception; } def g(): Int = try { 1 } finally { return 2 } //return 2 public int g() { int exceptionResult1 = 0; exceptionResult1 = 1; 2; return 2; Exception exception; exception; return 2; } |
|
返回顶楼 | |