Kotlin's Road - Starting Chapter

Posted by metalenchantment on Thu, 16 May 2019 17:06:36 +0200

Summary

At the 2017 Google Developers Conference, Google officially listed kotlin as its official language. So, what's the power of kotlin? In short, using kotlin can make the code more concise and readable, while supporting functional programming, 100% compatible with the old development language - Java, and there are many practical grammar sugar. Know about There is also the bull debate about kotlin, which has different opinions, but personally, kotlin is the trend of the times. If you think that kotlin can only be used to develop Android, it's too small to see its usefulness. Kotlin can be used not only to develop Android, but also to develop back-end service, front-end and so on. Is it very powerful? According to the god's revelation, kotlin may also support ios development in the future, because it is so similar to swift grammar?

data

Do you dare to say that you are not interested? Can't wait to learn? What, how? Personally speaking? Official documents Is the best learning material, if not enough, you can see the official recommendation of the basic good books:,, etc., although all foreign books, but the explanation is very thorough and vivid. Click here to download the full PDF version of the official document

Common usage

Here is a brief comparison of common usage in java development with kotlin:

  • for cycle:

In Java, we write a for loop as follows:

List<String> list = new ArrayList<String>();
list.add("red");
list.add("green");
list.add("blue");
for(int i=0;i<list.size();i++){
    System.out.println(list.get(i));
}

In kotlin, we can write as follows:

val list = listOf("red", "green", "blue")
for (item in list) {
    println(item)
}
  • Conditional statements in a variety of situations:

In Java, when we encounter a variety of conditions, we usually replace if-else statements with switch statements, such as:

private void test(int sign){
        switch (sign){
            case 0:

                System.out.println("this is 0");

                break;

            case 1:

                System.out.println("this is 1");

                break;

            case 2:

                System.out.println("this is 2");

                break;
            default:
                throw new IllegalArgumentException("out of range!");
        }
    }

In kotlin, we can even do this:

fun describe(obj: Any): String =
    when (obj) {
        1 -> "One"
        "Hello" -> "Greeting"
        is Long -> "Long"
        !is String -> "Not a string"
        else -> "Unknown"
}
  • Interval usage:
    If we need to filter and sort the known numbers simply, we can use for and if-else statements in Java, and kotlin can use this:
for (i in 4 downTo 1 step 2) print(i) 
// The output is: "42"

We can also use the in operator to determine whether an element is included in a collection:

when {
     "orange" in list -> println("juicy")
     "apple" in list -> println("apple is fine too")
}
  • Various expressions:
    In the past, if we need to use conditional or control statements to get the return value in Java, we usually need to implement it inside the function, while kotlin can be implemented directly through expressions, such as:
fun transform(color: String): Int {
    return when (color) {
       "Red" -> 0
       "Green" -> 1
       "Blue" -> 2
       else -> throw IllegalArgumentException("Invalid color param value")
    }
}

Or so:

fun foo(param: Int) {
    val result = if (param == 1) {
        "one"
    } else if (param == 2) {
        "two"
    } else {
        "three"
    }
}
  • Type detection:
    We can use the is operator to detect whether an expression is an instance of a certain type:
fun getStringLength(obj: Any): Int? {
     // obj converts to String type in & & right
     if (obj is String && obj.length > 0) {
        return obj.length
     }
     return null
}
  • Use lambda expressions to filter and map sets:
fruits
     .filter { it.startsWith("a") }
     .sortedBy { it }
     .map { it.toUpperCase() }
     .forEach { println(it) }

......

Last

Having seen so many kotlin usages, what do you think of the language? Of course, I just listed a few common grammatical sugars in kotlin, which are far more powerful than that. More usages can be found in official documents. Later, I will record their usages in special topics and finally show them through an Android project.

If you have more suggestions and questions, you are welcome to leave a message for discussion and join the Android Development Family.

Topics: Java Android Google Programming