从forEachLine返回

时间:2017-05-22 08:49:31

标签: closures kotlin

我有这个方法

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

如何退出封闭?

2 个答案:

答案 0 :(得分:3)

您可以使用文件中的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
}

答案 1 :(得分:2)

之前的示例有效,因为forEachinline 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
}