Click “blue wechat name” under the title to quickly follow
Are you still using Java? Now is the time to start using a new programming language. Have you been tempted since Kotlin became the official language of Google?
I want to tell you about a new programming language called Kotlin and explain why you should consider using it for your next project. I used to love using JAVA, but when I used Kotlin myself last year, I really didn’t think that JAVA was a better choice (linguistically).
Kotlin was developed by JetBrains. JetBrains actually develops IDES. Examples include IntelliJ and ReSharper. It really shines through Kotlin, who is concise and pragmatic and makes coding a satisfying and effective experience.
Although Kotlin can compile JavaScript and machine code. But I’ll focus on the original environment (JVM)
So here are a few reasons (in no particular order) why you should switch to Kotlin development
Interoperability with Java
Kotlin is 100% interoperable with JAVA, which means you can use Kotlin to develop your older JAVA projects. All your favorite Java frameworks can continue to be used. And some of the Kotlin frameworks you’ve written can easily serve your Java friends.
2. Familiar grammar
Kotlin is not an academic (programming) strange (elusive) language. Programmers from the OOP(Object-oriented programming language) world are familiar with this. And it’s more or less understandable. Of course, there are certain differences with Java. Such as constructors, or variable declarations such as val and var.(The following code snippet provides some basic explanations.)
Class Foo {val b: String = "b" // Val means unmodifiable can't change 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 }
Copy the code
3. String difference
It’s as if there’s a smarter, more readable Java version of String.format() built in.
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
4. Type inference
Kotlin will infer what type you want (you’ll feel better reading the code)
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
Copy the code
5. Smart casting
The Kotlin compiler tracks your logic to do automatic conversion types, which means there won’t be too much instanceof detection (in explicit conversion)
if (obj is String) {
print(obj.toUpperCase()) // obj is now known to be a String
}
Copy the code
6. Intuitive equality
You can stop using equals() to determine equality, because the == operator will check for structural equality.
val john1 = Person("John")
val john2 = Person("John")
john1 == john2 // true (structural equality)
john1 === john2 // false (referential equality
Copy the code
Default parameters
Methods that do not need to define several similar parameters
fun build(title: String, width: Int = 800, height: Int = 600) { Frame(title, width, height) }
Copy the code
Named parameters
In combination with the default parameters, the named parameters eliminate the constructor.
build("PacMan", 400, 300) // equivalent build(title = "PacMan", width = 400, height = 300) // equivalent build(width = 400, height = 300, title = "PacMan") // equivalent
Copy the code
When expression
The switch statement was replaced 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") in 5.. 10 -> print("x is 5, 6, 7, 8, 9, or 10") else -> print("x is out of range") }
Copy the code
It can be an expression or a statement, with or without arguments
val res: Boolean = when { obj == null -> false obj is String -> true else -> throw IllegalStateException() }
Copy the code
Ten, attributes,
Public parameters custom set&get behavior, which means we can prevent code bloat (getters&setters brings)
class Frame { var width: Int = 800 var height: Int = 600 val pixels: Int get() = width * height }
Copy the code
11. Data Classes (similar to Javabeans)
A normal data Bean(POJO) has toString(), equals(), hashCode(), and copy() and does not exceed 100 lines of code like Java
data class Person(val name: String, var email: String, var age: Int) val john = Person("John", "[email protected]", 112)
Copy the code
Operator overloading
A set of predefined 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
Destructuring Declarations (Destructuring Declarations)
You can deconstruct some objects, which is useful when iterating over data sets
for ((key, value) in map) { print("Key: $key") print("Value: $value") }
Copy the code
14. Ranges
Easy readability
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) {... }
Copy the code
15. Extended methods/functions
Remember the first time you used List sorting in Java? You can’t find a sort method to sort so you have to consult your teacher or Google to get the collections.sort () method. And then later when you’re using a String maybe you’ll write a helper class to help you get what you want, because you don’t know there’s stringutils.capitalize ()
If there is only one way to add new functionality to an old class, then your IDE will help you find that functionality in your code, which Kotlin makes easy.
fun String.format(): String { return this.replace(' ', '_') } val formatted = str.format()
Copy the code
The library extends the functionality of Java primitive types, which strings need in particular:
str.removeSuffix(".txt") str.capitalize() str.substringAfterLast("/") str.replaceAfter(":", "classified")
Copy the code
Sixteen, null value security
Java is a language that should be called almost statically typed. In Java, variables of type String are not guaranteed to reference String(safely) – It can be referred to as NULL, and even though we’re used to this type, it negates the security of static type checking, so Java developers won’t be able to avoid NPEs.(NullPointerException) or try to avoid (somewhat more work)Kotlin by distinguishing between non-null types and Null type to solve this problem. By default, the type is non-empty, and one can be added by default? For example:
var a: String = "abc" a = null // compile error var b: String? = "xyz" b = null // no problem
Copy the code
When you access an empty variable,Kotlin will enforce NPES(NullPointerException)
val x = b.length // compile error: b might be null
Copy the code
Although this may seem a bit tedious, it is really easy to develop because of its features, and we can intelligently convert empty types to non-empty types for our use.
if (b == null) return val x = b.length // no problem
Copy the code
And we can safely use it when we evaluate to null (instead of throwing a null pointer exception).
val x = b? .length // type of x is nullable Int
Copy the code
Security calls can be chained together to avoid the nested if-not-NULL checks we sometimes write in other languages, and if we want a default value other than null, we can use the Elvis operator
val name = ship? .captain? .name ?: "unknown"
Copy the code
If this does not apply to you and you need an NPE, you will have to explicitly ask for it
val x = b? .length ? : throw NullPointerException() // same as below val x = b!! .length // same as above
Copy the code
Better Lambda expressions
Boy,Kotlin supports Lambda better, based on his clever good language design, straightforward syntax, readability and simplicity.
Val sum = {x: Int, y: Int -> x + y} // type: (Int, Int) -> Int val res = sum(4,7) // res == 11
Copy the code
To better illustrate the following
-
1. If the lambda expression takes the last or only argument to a method, move or omit the method parentheses
-
2. If we choose not to declare a single-argument-lambda, it will be declared implicitly as it.
numbers.filter({ x -> x.isPrime() }) numbers.filter { x -> x.isPrime() } numbers.filter { it.isPrime() }
Copy the codeAnd it also allows us to write much cleaner and prettier code:
persons .filter { it.age >= 18 } .sortedBy { it.name } .map { it.email } .forEach { print(it) }
Copy the codeThe perfect combination of Kotlin’s Lambda system features makes it an ideal choice for DSL creation. Check out Anko’s DSL example, designed to serve Android development.
ErticalLayout {padding = dip(30) editText {hint = "Name" textSize = 24f} editText {hint = "Password" textSize = 24f } button(" Login ") {textSize = 26f}}
Copy the code
IDE support
If you plan to start using Kotlin, you have several options, but I strongly recommend using the IntelliJ software that comes bundled with Kotlin. To take a small example, this thing popped up the first time I tried to copy and paste some Java code from StackOverflow.
Author: if LanMingYue link: http://www.jianshu.com/p/ec841df96f1e
Why you should totally switch to Kotlin
Related to recommend
AspectJ practical implementation of AOP programming data trace – free burying point
Technology – Thinking – growth
END