从forEachLine返回

我有这个方法

private fun getDeviceType(): Device { ExecuteCommand().forEach { if (it == "my search string") { return Device.DEVICE_1 } } return Device.UNKNOWN } 

其中ExecuteCommand()实际上是一个cat file并返回文件内容的列表。 所以不是执行一个shell命令,而是将其改为

 private fun getDeviceType(): Device { File(PATH).forEachLine { if (it == "my search string") { return Device.DEVICE_1 } } return Device.UNKNOWN } 

但现在编译器抱怨说return is not allowed here

我怎样才能退出封闭?

前面的例子是有效的,因为forEach是一个内联方法 ,而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 } 

您可以使用文件Sequence<String>

 private fun getDeviceType(): Device { File(PATH).useLines { lines -> lines.forEach { if (it == "my search string") { return Device.DEVICE_1 } } } return Device.UNKNOWN } 

对于较小的文件,也可以将这些行读入列表中:

 private fun getDeviceType(): Device { File(PATH).readLines().forEach { if (it == "my search string") { return Device.DEVICE_1 } } return Device.UNKNOWN }