在Kotlin的Runnable SAM中不能有返回?

我对这段代码有以下错误,这对我没有任何意义:

fun spawnWorker(): Runnable { return Runnable { LOG.info("I am a potato!") return } } 

我的IDE对我说:

在这里输入图像描述

但Runnable接口说:否则:

 @FunctionalInterface public interface Runnable { public abstract void run(); } 

为什么我不能在那里得到回报,但没有任何回报,它编译得很好:

 fun spawnWorker(): Runnable { return Runnable { LOG.info("I am a potato!") } } 

一个普通的返回从最近的封闭函数或匿名函数返回。 在你的例子中,返回是非本地的,并且从spawnWorker而不是从Runnable SAM适配器返回。 对于本地退货,请使用带标签的版本:

 fun spawnWorker(): Runnable { return Runnable { LOG.info("I am a potato!") return@Runnable } } 

您正在使用lambda-to-SAM转换,因此试图从lambda语句返回,这是不允许有自己的返回。

你的代码

 fun spawnWorker(): Runnable { return Runnable { LOG.info("I am a potato!") } } 

意思是一样的

 fun spawnWorker(): Runnable { return { LOG.info("I am a potato!") } } 

比较它返回一个对象,这是从Java的直接翻译:

 fun spawnWorker(): Runnable { return object : Runnable { override fun run() { LOG.info("I am a potato!") return // don't really need that one } } }