TIL: The brevity of Kotlin

I’ve started looking into JVM languages. As an exercise, I researched how to do a basic HTTP request - one trivial evaluation point of a language (i.e. how simply or comfortably this built-in feature is made available).

In Java, here’s one way to request a page:

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.InputStreamReader;
import java.io.BufferedReader;

public class Main {

    public static void main(String[] args) throws IOException {

        URL url = new URL("http://example.com");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
//      con.setRequestMethod("GET");    // this line is optional since GET is the default

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer content = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine);
        }
        in.close();

        System.out.println(content);

        con.disconnect();

    }
}

The following is one way to do it in Kotlin:

import java.net.URL

fun main(){
    println(URL("http://example.com").readText())
}

To be fair, I read that Kotlin was not built to be a “better Java” but I can see why some Java developers are interested in Kotlin.

Contents