java8的输入语句,Java 8:目标输入

While reading the article Target Typing and I'm getting a bit confused with the following paragraph:

ActionListener l = (ActionEvent e) -> ui.dazzle(e.getModifiers());

An implication of this approach is that the same lambda expression can

have different types in different contexts:

Callable c = () -> "done";

PrivilegedAction a = () -> "done";

In the first case, the lambda expression () -> "done" represents an

instance of Callable. In the second case, the same expression

represents an instance of PrivilegedAction.

The compiler is responsible for inferring the type of each lambda

expression. It uses the type expected in the context in which the

expression appears; this type is called the target type. A lambda

expression can only appear in a context whose target type is a

functional interface.

Can you explain me these points in relation with the quoted paragraph in a simple way:

target type

context

I will really appreciate it if you also provide code snippets.

解决方案

Context

Context is the way an expression is used within the code. It's not just lambda expressions - it's any expression, like a+b, a++ or Math.random().

Examples of possible contexts:

Assignment: take the expression a+b. If you assign it to a variable, it is used in an assignment context:

c = a+b;

Argument to a method or constructor:. This is when you pass it to some method call:

System.out.println(a+b);

Return value: When you are using the expression in a return statement:

return a+b;

Index to an array: When your expression is the index of an array:

x[a+b] = 3;

Target type

The target type is the type expected in the given context. For example, if you have a method defined as:

public int myMethod() { ... }

then any expression in a return statement in its body is expected to have the type int. So if you have this:

return a+b;

inside myMethod, it's expected that a+b will resolve to an int or something that's assignable to an int.

Now, suppose you have this method:

public void anotherMethod( double d );

Then when you call it, and pass an expression as an argument, that expression is expected to be of type double. So a call like:

anotherMethod(a+b);

expects a+b to resolve to a double. That's its target type.

In your example

In the declaration:

Callable c = () -> "done";

the expression is the lambda expression () -> "done". It is used in an assignment context (it is assigned to c). And the target type is Callable because that's what is expected when you assign anything to c.

For a more formal discussion, refer to the Java Language Specification, Chapter 5.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值