我有这个方法
private fun getDeviceType(): Device {
ExecuteCommand().forEach {
if (it == "my search string") {
return Device.DEVICE_1
}
}
return Device.UNKNOWN
}
其中ExecuteCommand()
实际上执行一个cat文件
并返回文件内容的列表。因此,我没有执行 shell 命令,而是将其更改为
private fun getDeviceType(): Device {
File(PATH).forEachLine {
if (it == "my search string") {
return Device.DEVICE_1
}
}
return Device.UNKNOWN
}
但现在编译器提示此处不允许返回
。
如何退出关闭?
最佳答案
前一个示例之所以有效,是因为 forEach
是 inline method ,而 forEachLine
则不是。但是,您可以这样做:
private fun getDeviceType(): Device {
var device = Device.UNKNOWN
File(PATH).forEachLine {
if (it == "my search string") {
device = Device.DEVICE_1
return@forEachLine // Exits the closure only
}
}
return device
}
关于closures - 从 forEachLine 返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44108489/