Explain how this lambda can be assigned to an Iterable

前端 未结 2 1743
离开以前
离开以前 2021-01-04 10:21

I came across some clever code to convert an Iterator to a Stream from Karol on this post. I have to admit that I don\'t completely understand how the lambda is allowed to b

2条回答
  •  别那么骄傲
    2021-01-04 10:53

    As you've pointed out, assignment from a lambda expression is only valid if the target is a functional interface. This is described in section 15.27.3 of the JLS: Type of a Lambda Expression.

    A lambda expression is compatible in an assignment context, invocation context, or casting context with a target type T if T is a functional interface type (§9.8) and the expression is congruent with the function type of the ground target type derived from T.

    Jumping to section 9.8: Functional Interfaces, we can see the definition of a functional interface.

    A functional interface is an interface that has just one abstract method (aside from the methods of Object), and thus represents a single function contract.

    Iterable does satisfy the criteria for a functional interface, because it has only one abstract method: iterator(). (The 2 additional default methods do not violate the criteria, because they are not abstract.) Therefore, the assignment is valid.

提交回复
热议问题