closureskotlin

Return from forEachLine


I have this method

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

where ExecuteCommand() actually does a cat file and returns a list of the file contents. So instead of executing a shell command, I changed it to

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

But now compiler complains that return is not allowed here.

How can I exit from the closure?


Solution

  • The former example works because forEach is an inline method, while forEachLine is not. However, you can do this:

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