• Why you should totally switch to Kotlin
  • Magnus Vinther
  • The Nuggets translation Project
  • Permanent link to this article: github.com/xitu/gold-m…
  • Translator: ALVINYEH
  • Proofreader: Starrier, Sergey Cheung

Why should you start using Kotlin

It’s time to start using modern programming languages

I want to tell you about a new programming language called Kotlin, and why you should consider using it for your next project. In the past, I preferred Java, but last year I found myself writing code in Kotlin whenever I wanted. At this point, I really can’t think of a situation where Java would be the better choice.

It was developed by JetBrains, the same people behind IDEs products like IntelliJ and ReSharper, and Kotlin is really popular. Its practicality and simplicity make coding a satisfying and efficient experience.

Although Kotlin can compile to JavaScript and machine code quickly, I’ll focus on its main environment, the JVM.

So, here are some reasons why you should start using Kotlin (in no particular order) :

0 #Java interoperability

Kotlin and Java are 100% interoperable. You can use Kotlin to continue your previous Java projects. All your favorite Java frameworks will still work, and any framework you write in Kotlin can be used by your Java-loving friends.

1 # Familiar grammar

Kotlin is not a strange language born in academia. Its syntax will be familiar to any programmer from the OOP world, and will be more or less understandable from the start. Of course, Java also has some differences, such as overwriting constructors or declarations of val and var variables. The following code covers most of the basics:

class Foo {

    val b: String = "b"Var I: Int = 0 var fun = funhello() {
        val str = "Hello"
        print("$str World")
    }

    fun sum(x: Int, y: Int): Int {
        return x + y
    }

    fun maxOf(a: Float, b: Float) = if (a > b) a else b

}
Copy the code

2 # String interpolation

It’s like a smarter, more readable version of Java’s String.format() was built into the language:

val x = 4
val y = 7
print("sum of $x and $y is ${x + y}")  // sum of 4 and 7 is 11
Copy the code

3 #Type inference

Kotlin will infer the type when you need it, which effectively improves readability:

val a = "abc"Val c: Double = 0.7 // Explicit declaration type val D: List<String> = ArrayList() // Explicit declaration typeCopy the code

4 #Intelligent transformation

If possible, Kotlin’s compiler tracks your logic and automatically converts the type, which means a lot less instanceof checking and explicit conversions:

if (obj is String) {
    print(obj.toupperCase ()) // obj is now considered a String. }Copy the code

5 #Intuitive Equals

You can no longer display calls to equals(), because the == operator now checks whether the expression structure is the same:

val john1 = Person("John")
val john2 = Person("John")

john1 == john2    // true(same structure) john1 === john2 //false(Quote equal)Copy the code

6 #The default parameters

There is no need to define several similar methods with different parameters:

fun build(title: String, width: Int = 800, height: Int = 600) {
    Frame(title, width, height)
}
Copy the code

7 #Named parameters

Combined with the default arguments, named arguments eliminate the need for builders:

build("PacMan", 400, 300) // Equivalent build(title ="PacMan"Build (width = 400, height = 300, title = 300"PacMan"/ / equivalentCopy the code

8 #When the expression

Replace the switch case expression with a more readable and flexible WHEN expression:

when (x) {
    1 -> print("x is 1"2 - >)print("x is 2") 3, 4 - >print("x is 3 or 4")
    in5.. 10 - >print("x is 5, 6, 7, 8, 9, or 10")
    else -> print("x is out of range")}Copy the code

It can be used in expressions or statements, with or without arguments:

val res: Boolean = when {
    obj == null -> false
    obj is String -> true
    else -> throw IllegalStateException()
}
Copy the code

9 # attribute

Custom setter and getter methods are added to the public scope, which means we can avoid inadvertantly bloated code with [get and set behavior].

class Frame {
    var width: Int = 800
    var height: Int = 600

    val pixels: Int
        get() = width * height
}
Copy the code

10 # Data classes

It’s a POJO with toString(), equals(), hashCode(), and copy() methods, and unlike Java, it doesn’t take up 100 lines of code:

data class Person(val name: String,
                  var email: String,
                  var age: Int)

val john = Person("John"."[email protected]", 112).Copy the code

11 #Operator overloading

Predefined sets of operators can be overridden to improve readability:

data class Vec(val x: Float, val y: Float) {
    operator fun plus(v: Vec) = Vec(x + v.x, y + v.y)
}

val v = Vec(2f, 3f) + Vec(4f, 1f)
Copy the code

12 #Deconstruction statement

Some objects can be deconstructed, but this is useful for iterating over maps:

for ((key, value) in map) {
    print("Key: $key")
    print("Value: $value")}Copy the code

13 #The scope of

For readability:

for (i in 1..100) { ... } 
for (i in 0 until 100) { ... }
for (i in2.. 10 step 2) { ... }for (i in 10 downTo 1) { ... } 
if (x in 1..10) { ... }
Copy the code

14 # Extension function

Remember the first time you sorted a List in Java? You can’t find a sort() function, so you’ll have to ask your tutor or learn to use collections.sort () on Google. Later when you had to use String strings, you wrote a helper function yourself because you didn’t know you could use Stringutils.capitalize ().

If there’s only one way to add a new function to an old class, it’s the way your IDE code completes to help you find the right one. Here’s exactly what you can do at Kotlin:

fun String.replaceSpaces(): String {
    return this.replace(' '.'_')
}

val formatted = str.replaceSpaces()
Copy the code

The library extends Java’s native types, especially strings:

str.removeSuffix(".txt")
str.capitalize()
str.substringAfterLast("/")
str.replaceAfter(":"."classified")
Copy the code

15 # Null security

We should call Java an almost statically typed language. A String variable is not guaranteed to point to the same type as String — it may point to NULL. Although we’re used to this, it negates the safety of static type checking. As a result, Java developers have to live in constant fear of null-pointer exceptions.

Kotlin solves this problem by distinguishing between non-null types and nullable types. By default, the type is non-empty, which can be done by adding? Make a variable empty:

var a: String = "abc"Var b: String? ="xyz"B = null // Compilation succeededCopy the code

Whenever you access a variable of a non-null type, Kotlin forces you to prevent null-pointer exceptions:

Val x = b.length // compilation error: variable B may be emptyCopy the code

While this may seem like a lot of trouble, it’s a breeze thanks to some of its features. We can still intelligently convert a nullable variable to a non-nullable type whenever possible:

if (b == null) returnVal x = b.length // No problemCopy the code

Can we also use a secure one? The. Character to estimate whether the variable is null, rather than throwing a null pointer:

val x = b? .length // The type of variable x is a nullable IntCopy the code

Security calls can also be called together to avoid the nested if-not-NULL checks we sometimes write in other languages. If we want a default value other than null, we can use the Elvis operator, right? : :

val name = ship? .captain? .name ?:"unknown"
Copy the code

If this doesn’t work for you, and you need a null-pointer exception, you must display the declaration:

val x = b? .length ? : throw NullPointerException() .length with / /Copy the code

16 # Better Lambdas

Oh brother, this is a good Lambada system – thanks to some clever design choices that give it the perfect balance between readability and simplicity. Grammar is first straightforward:

val sum = { x: Int, y: Int -> x + y }   // type: (Int, Int) -> Int
val res = sum(4,7)                      // res == 11
Copy the code

Here’s the good part:

  1. If lambda is the last or only argument to a method, the parentheses can be moved or omitted.
  2. If we do not declare an argument to the single-argument lamda, it is implicitly declared to beit.

Taken together, these examples give the following three lines of code the same effect:

numbers.filter({ x -> x.isPrime() })
numbers.filter { x -> x.isPrime() }
numbers.filter { it.isPrime() }
Copy the code

This allows us to write neat function code — look at the beauty of it:

persons
    .filter { it.age >= 18 }
    .sortedBy { it.name }
    .map { it.email }
    .forEach { print(it) }
Copy the code

Kotlin’s Lambda system, combined with extension functions, makes it ideal for DSL creation. Take a look at an example of Anko’s DSL, which aims to improve Android development:

VerticalLayout {padding = dip(30) editText {hint = "Name" textSize = 24f} editText {hint = "Password" textSize = 24f } button(" Login ") {textSize = 26f}}Copy the code

17 #IDE support

If you’re going to start using Kotlin, you have a number of environments to choose from, but I highly recommend using IntelliJ bundled with Kotlin because its functionality demonstrates the benefits of having the same people designing both the language and the IDE.

To give you a small but clever example, this window pops up the first time I try to copy some Java code from Stack Overflow:

If you paste Java code into Kotlin’s file, IntelliJ will notice.


That’s all for now. Thanks for reading! This is my first post on Medium. If you still can’t believe Kotlin, here are some more convincing articles:

  • Kotlin on Android. Now official
  • Why Kotlin is my next programming language
  • Scala vs Kotlin
  • Swift is like Kotlin
  • The Road to Gradle Script Kotlin 1.0
  • Introducing Kotlin support in Spring Framework 5.0
  • 10 cool things about Kotlin
  • Kotlin full stack application example
  • Why I abandoned Java in favour of Kotlin
  • I used Kotlin at Hackathon
  • From Java to Kotlin
  • Kotlin Idioms

The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.