为什么不能?
mputeIfAbsent(,s - > throw new IllegalArgumentException(fail));是由于假设编译器会在这个实例中返回一个int,所以这样做是由于解决方案
Java语言规范描述了一个lambda表达式的主体
lambda体是单个表达式或块(§14.2)。
然而,
throw new IllegalArgumentException(fail)是 throw 语句 ,而不是表达式。因此,编译器将其拒绝为lambda表达式的正文。
您可以下载兔子洞,了解所有类型的表达式,这里(遵循语法)。
I understand that a lambda in java cannot throw a checked exception, but can throw a RuntimeException, but why does the below code require brackets?
Map<String, Integer> m = new HashMap<>(); Integer integer = mputeIfAbsent("", s -> {throw new IllegalArgumentException("fail");});Why can't you have?
mputeIfAbsent("", s -> throw new IllegalArgumentException("fail"));Is it due to the assumption of the compiler that it would return in this instance an int, so therefor can't have a return of an exception, even though its thrown?
解决方案The Java Language Specification describes the body of a lambda expression
A lambda body is either a single expression or a block (§14.2).
This, however,
throw new IllegalArgumentException("fail")is the throw statement, not an expression. The compiler therefore rejects it as the lambda expression's body.
You can go down the rabbit hole and learn what all the types of expressions are, here (follow the grammar).
更多推荐
为什么引发运行时异常的Java Lambda需要括号?
发布评论