Exceptions in Kotlin

Checked exceptions force handling, even if we don't need this. This is the root of many problems and that's why Kotlin doesn't have checked exceptions. Let's imagine that we want to implement our own class for logging that implements the Appendable interface from the java.lang package:

class Logger implements Appendable {

@Override
public Appendable append(CharSequence csq) throws IOException {
throw new NotImplementedException();
}

@Override
public Appendable append(CharSequence csq, int start, int end) throws IOException {
throw new NotImplementedException();
}

@Override
public Appendable append(char c) throws IOException {
throw new NotImplementedException();
}
}

We can use this class to print logs as follows:

public static void main(String[] args) {
Logger logger = new Logger();
logger.append("Start...");
//....
logger.append("Done...")
}

This code doesn't compile because methods from the Appendable interface throw a checked exception. Furthermore, we have to wrap this code into the try { ... } catch { ... } block. This can be very annoying if we use the append method in lambda:

Arrays.asList(0, 1, 3, 4).forEach(integer -> {
try {
logger.append(integer.toString());
} catch (IOException e) {
e.printStackTrace();
}
});

The preceding snippet demonstrates that a lambda with the try { ... } catch { ... } block inside doesn't look concise.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.253.31