Java 为什么允许这样做?从lambda(作为接口的缺失方法)到接口的隐式转换

Java 为什么允许这样做?从lambda(作为接口的缺失方法)到接口的隐式转换,java,lambda,type-conversion,Java,Lambda,Type Conversion,背景:我是Java新手(有C++背景) 因此,假设我有一个实现了迭代器接口的类: public class C implements Iterator<concreteType>{ // implementation } 是的,这是允许的。(这被认为不是特别好的做法,因为Iterable没有注释@functionalterface,这意味着它不打算以这种方式使用。) 将函数对象分配给Iterable似乎没有意义 为什么??Iterable实际上是迭代器的供应商。你得到的相当

背景:我是Java新手(有C++背景)

因此,假设我有一个实现了
迭代器
接口的类:

public class C implements Iterator<concreteType>{
    // implementation
}
是的,这是允许的。(这被认为不是特别好的做法,因为
Iterable
没有注释
@functionalterface
,这意味着它不打算以这种方式使用。)

将函数对象分配给Iterable似乎没有意义

为什么??Iterable实际上是迭代器的供应商。你得到的相当于

new Iterable<ConcreteType>() {
  @Override public Iterator<ConcreteType> iterator() {
    return new C<ConcreteType>();
  }
}
newiterable(){
@重写公共迭代器迭代器(){
返回新的C();
}
}
我很难理解你在说什么,但实际上发生的事情似乎与你提到的第三种可能性最接近。您正在创建一个新的
Iterable
,当请求使用迭代器时,它将创建一个
new C()
,并返回它。

为什么“将函数对象分配给Iterable对我来说没有意义”是因为这两种类型实际上用于不同的事情:一种是提供对某个对象的访问,另一个是提供行动。甚至认为“行动”原则上可能是“提供访问”,这真的很奇怪。
import java.util.Iterator;

public class C implements Iterator<Integer>{

    private Integer nextInt;
    private Integer i;

    public C() // to test if the constructor is actually called
    {
        System.out.println("C ctor");
    }

    public boolean hasNext()
    {
        return nextInt != null;
    }

    public Integer next()
    {
       return nextInt;
    }

    public static void main(String [] args)
    {
        Iterable<Integer> coll = () -> new C();
    }
}
new Iterable<ConcreteType>() {
  @Override public Iterator<ConcreteType> iterator() {
    return new C<ConcreteType>();
  }
}