📜 ⬆️ ⬇️

Why you should completely switch to Kotlin


I want to tell you about a new programming language called Kotlin, and explain why you should use it in your next project. I used to prefer Java, but last year I write on Kotlin wherever possible. And at the moment I can’t imagine a situation in which it would be better to choose Java.


Kotlin is developed in JetBrains , and the participation of the same people in creating IDE kits, such as IntelliJ and ReSharper , is clearly visible in the language itself. It is pragmatic and brief , so writing code turns into a pleasant and efficient process.


Although Kotlin is compiled into JavaScript and will soon be compiled into native code , I will focus on its primary environment, the JVM .


So, several reasons why you should completely switch to Kotlin (the order is random):


0 # Java Compatibility


Kotlin is 100% Java compatible . You can literally continue to work on your old Java project, but already using Kotlin. All your favorite Java frameworks will also be available , and, whatever framework you write, Kotlin will be easily accepted by a stubborn Java lover.


1 # Familiar syntax


Kotlin — - , . , , - . , Java val var. :


class Foo {

    val b: String = "b"     // val means unmodifiable
    var i: Int = 0          // var means modifiable

    fun hello() {
        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

}

2#


String.format() Java, :


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

3#


Kotlin , , :


val a = "abc"                         // type inferred to String
val b = 4                             // type inferred to Int

val c: Double = 0.7                   // type declared explicitly
val d: List<String> = ArrayList()     // type declared explicitly

4# (Smart Casts)


Kotlin , . . instanceof :


if (obj is String) {
    print(obj.toUpperCase())     // obj is now known to be a String
}

5# (Intuitive Equals)


equals(), == :


val john1 = Person("John")
val john2 = Person("John")
john1 == john2    // true  (structural equality)
john1 === john2   // false (referential equality)

6#


:


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

7#


:


build("PacMan", 400, 300)                           // equivalent
build(title = "PacMan", width = 400, height = 300)  // equivalent
build(width = 400, height = 300, title = "PacMan")  // equivalent

8# When


when:


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

(expression), (statement), :


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

9#


set & get, . . .


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

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

10# Data Class


POJO- toString(), equals(), hashCode() copy(), , Java, 100 :


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

val john = Person("John", "john@gmail.com", 112)

11# (Operator Overloading)


, :


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)

12# (Destructuring Declarations)


, , , map:


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

13# (Ranges)


:


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

14# - (Extension Functions)


, List Java? sort(), Collections.sort(). , , , StringUtils.capitalize().


, IDE . Kotlin:


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

val formatted = str.format()

Java-, String:


str.removeSuffix(".txt")
str.capitalize()
str.substringAfterLast("/")
str.replaceAfter(":", "classified")

15# Null


Java . String String — null. , , Java- NPE.


Kotlin , null. null, , ?:


var a: String = "abc"
a = null                // compile error

var b: String? = "xyz"
b = null                // no problem

Kotlin NPE, , null:


val x = b.length        // compile error: b might be null

, , . , , null, :


if (b == null) return
val x = b.length        // no problem

?., null NPE:


val x = b?.length       // type of x is nullable Int

, --null, . null-, elvis- ?::


val name = ship?.captain?.name ?: "unknown"

NPE, :


val x = b?.length ?: throw NullPointerException()  // same as below
val x = b!!.length                                 // same as above

16#


—  . :


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

:


  1. , .
  2. , it.

:


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

, :


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

, -, Kotlin DSL. Anko — DSL, Android-:


verticalLayout {
    padding = dip(30)
    editText {
        hint = “Name”
        textSize = 24f
    }
    editText {
        hint = “Password”
        textSize = 24f
    }
    button(“Login”) {
        textSize = 26f
    }
}

17# IDE


, Kotlin, IntelliJ, Kotlin — , , IDE.
: , Java- Stack Overflow:


image
IntelliJ , Java- Kotlin




, ! Kotlin, :



')

Source: https://habr.com/ru/post/329294/


All Articles