0
点赞
收藏
分享

微信扫一扫

为什么要学习 Kotlin ?


为什么要学习 Kotlin ?_软件开发

为什么我喜欢 Kotlin ?

我想解释一下为什么我更喜欢Kotlin而不是Java。

简而言之,在不牺牲性能或安全性的前提下,许多无数的Kotlin功能使代码比Java更加简洁易懂。

Kotlin编译为字节码,因此其性能与Java一样好。它具有与Java相同的编译时检查(还有更多内容,例如内置的可空性检查)。最重要的是,Kotlin的语言功能和标准库功能可实现简洁有效的代码。

简洁,因为这是提高程序员工作效率的关键因素。

最初是组装。每行代码仅给您提供整个程序的功能说明。这使得读取和写入都变得困难,因为您必须一次将如此多的代码保存在脑海中。

高级语言使我们可以在每一行代码中添加更多想法。例如,对列表进行排序在大多数现代语言中都是微不足道的。当每行代码获得更多功能时,编写较大的程序会更容易。

但是,我们不想在每行代码中尽可能多地包含想法。如果代码过于简洁,那么它也将变得难以理解。正则表达式就是这个问题的典型例子。简而言之,我仍然会定期与之抗争。

Lambda :

// All examples create a function object that performs upper-casing.
// So it's a function from String to String


val upperCase1: (String) -> String = { str: String -> str.toUpperCase() } // 1


val upperCase2: (String) -> String = { str -> str.toUpperCase() } // 2


val upperCase3 = { str: String -> str.toUpperCase() } // 3


// val upperCase4 = { str -> str.toUpperCase() } // 4


val upperCase5: (String) -> String = { it.toUpperCase() } // 5


val upperCase6: (String) -> String = String::toUpperCase // 6


println(upperCase1("hello"))
println(upperCase2("hello"))
println(upperCase3("hello"))
println(upperCase5("hello"))
println(upperCase6("hello"))

Higher-Order Functions:

fun calculate(x: Int, y: Int, operation: (Int, Int) -> Int): Int {  // 1
return operation(x, y) // 2
}


fun sum(x: Int, y: Int) = x + y // 3


fun main() {
val sumResult = calculate(4, 5, ::sum) // 4
val mulResult = calculate(4, 5) { a, b -> a * b } // 5
println("sumResult $sumResult, mulResult $mulResult")
}

在将Kotlin与Java进行比较时,Kotlin比Java更简洁。关键是Kotlin不会为了简洁而牺牲理解力。

Why Kotlin?

Concise

Drastically reduce the amount of boilerplate code

/*

Create a POJO with getters, setters, `equals()`, `hashCode()`, `toString()` and `copy()` in a single line:

*/

data class Customer(val name: String, val email: String, val company: String)

// Or filter a list using a lambda expression:

val positiveNumbers = list.filter { it > 0 }

// Want a singleton? Create an object:

object ThisIsASingleton {

val companyName: String = "JetBrains"

}

Safe

Avoid entire classes of errors such as null pointer exceptions

/*

Get rid of those pesky NullPointerExceptions, you know, The Billion Dollar Mistake

*/

var output: String

output = null   // Compilation error

// Kotlin protects you from mistakenly operating on nullable types

val name: String? = null    // Nullable type

println(name.length())      // Compilation error

// And if you check a type is right, the compiler will auto-cast it for you

fun calculateTotal(obj: Any) {

if (obj is Invoice)

obj.calculateTotal()

}

Interoperable

Leverage existing libraries for the JVM, Android, and the browser

/*

Use any existing library on the JVM, as there’s 100% compatibility, including SAM support.

*/

import io.reactivex.Flowable

import io.reactivex.schedulers.Schedulers

Flowable

.fromCallable {

Thread.sleep(1000) //  imitate expensive computation

"Done"

}

.subscribeOn(Schedulers.io())

.observeOn(Schedulers.single())

.subscribe(::println, Throwable::printStackTrace)

// Target either the JVM or JavaScript. Write code in Kotlin and decide where you want to deploy to

import kotlin.browser.window

fun onLoad() {

window.document.body!!.innerHTML += "<br/>Hello, Kotlin!"

}

Tool-friendly

Choose any Java IDE or build from the command line

早在2017年Google I / O大会上,Google宣布将 Kotlin 作为Android开发的官方编程语言后,Kotlin 开发者社区一直在快速增长。Stack Overflow 的2018年开发者调查显示Kotlin是排名第二的编程语言。纵观硅谷,Netflix、Slack、Pinterest和Lyft等知名公司已经在使用Kotlin。这也意味着,对于 Java 程序员和 Android 应用开发者来说,仅仅掌握 Java 是不够的,你还应该学习 Kotlin,才能追上技术发展趋势,在工作中更加游刃有余。

为什么要学习 Kotlin ?_java_02

为什么要学习Kotlin ?

  • Google发布申明,目前已经有​​35%​​​的​​Android专业开发人员​​​使用​​kotlin​​(爆发式增长)
  • Google与Oracle源于Android的恩怨持续已久,也一直想要找一种语言代替​​Java​
  • ​Java​​​以后要开始收费了,可能导致一部分公司放弃​​Java​
  • 当前已经有许多公司的招聘要求中,要求开发人员需要会​​kotlin​
  • ​kotlin​​​的学习成本并不是很高,从​​Java​​​转​​kotlin​​​,一般​​一周时间​​​就足以完成,且​​kotlin​​​与​​Java​​​可以相互调用,觉得​​kotlin​​​解决不了的地方,仍然可以使用​​Java​​编写(非常人性化)

为什么要学习 Kotlin ?_人工智能_03

17 位谷歌 Android 开发专家是如何看待 Kotlin 的?

​​https://antonioleiva.com/google-kotlin/​​

为什么要学习 Kotlin ?_go_04

当 Kotlin 出现时,我立刻被它吸引了,因为它的很多语法特性让我想起了 Groovy。它既整洁又精炼。

Kotlin 另外一个显著的优点是具备扩展函数的能力,通过给 ​​Context​​​,​​Activity​​​ 和 ​​Date​​ 类添加扩展函数,使得我的代码简洁了很多,同时变得更加易于阅读。

通过使用 Kotlin,我的代码变得更好了。

它在很多情况下使得编码变成一件愉快的事情,相比之前,同样的情况下用 Java 语言编码将会感到痛苦和繁琐。

Kotlin 是极好的,我喜欢它,它是 Android 世界的一股清流。

我完全迷上了 Kotlin。工作中我们 100% 的使用 Kotlin 进行编码,包含线上产品的代码。事实上,无论何时何地只要能够使用 Kotlin 的地方我都会使用 Kotlin 进行编码,归功于 Kotlin 和 Java 的可互操作性,几乎可以说任何地方都可以使用 Kotlin。

对于那些停留在 Android 世界的开发者而言,Kotlin 是一个真正的规则改变者,它拥有很多我喜欢的特性:空类型安全,data classes,属性和懒加载属性,扩展函数,协程,不变性等等。

归功于 JetBrains,Kotlin 有很棒的 IDE 支持以及非常多的学习资料,甚至有在线的 REPL。

从 Java 转到 Kotlin 真的不需要费多大劲,而它的优点会很快呈现出来。

我认为 Kotlin 是一门非常棒的现代编程语言。它的学习曲线很平缓,你可能只需要花一天时间来学习它的语法,就可以用 Kotlin 写出一些代码,实现某些功能。Kotlin 写起来真的很过瘾,很好玩,而且很简洁,它具备其他现代语言的特性,它由 JetBrains 这样很专业的团队进行持续的开发,同时一直有社区的支持,因为它是开源的

一旦你开始用 Kotlin 进行编码,你将不想再使用 Java 进行编码????。

我的最大建议是记住 Kotlin 和 Java 并不是非此则彼的关系,相反,Kotlin 能够很好的和现有的 Java 代码协同工作,所以你可以一步一步的开始尝试使用 Kotlin。

Kotlin 是 Android 应用开发的未来

Kotlin 对 Android 开发的影响和三年前 Grade 对 Android 的影响非常相似。作为 Android 开发者社区,我们应该拥抱 Kotlin,传播 Kotlin,并让一大批的开发者来使用 Kotlin,因为我们值得拥有更好的方法来开发 APP,满足用户的需要并在工作中取得好成绩。

 

Kotlin 对于 Android 开发者而言是一股清流我喜欢它在 lambda 表达式上所做的工作

如果你是一名 Java 开发者,Kotlin 的语法对你而言是非常自然的。如果你是一名 Swift 开发者,也会有同样的感觉,而且你会很容易理解 Kotlin 的一些关键概念例如空类型。Kotlin 其他吸引我注意的特性如下:

  • 空类型:告诉你公司的业务人员你可以避免产品中三分之二的异常,这将是一件令人心动的事情。直到开始使用 Kotlin,你才意识到在 Java 中没有空类型是多么糟糕的一件事情。
  • 函数式编程:是的,Kotlin 正如 Scala 一样,支持函数式编程。
  • 默认和命名参数:再次的,如果你之前没有尝试过这种特性,你将永远不会知道它的可贵之处。在 Kotlin 中,你可以为一个函数的参数设置默认值,并为每个参数命名。这成倍的增加代码的可读性和易读性。
  • 智能的强制转换:厌倦了使用 ​​instanceof​​ 进行类型判断然后进行类型转换吧?它似乎总是非常多余的步骤,本应该很容易防止的。Kotlin 自动为你实现这些步骤。

Koltin 还有一堆的特性,可能需要几篇文章的篇幅来进行列举和深入介绍。总结来说:Koltin 是一门用于补充和完善 Java 不足的语言。对于 Java 开发者而言学习曲线很平缓。这不是一个非此即彼的问题,因为你可以在你的 Java 代码仓库中同时使用 Java 和 Kotlin。Kotlin 将会提高您的工作效率,从中长期来看,它将使你成为一名更好的程序员。

完整内容请参考:​​17 位谷歌 Android 开发专家是如何看待 Kotlin 的?​​

Kotlin是什么?

为什么要学习 Kotlin ?_编程语言_05

kotlin是来自JetBrains公司:

为什么要学习 Kotlin ?_java_06

以圣彼得堡附近的kotlin岛命名。他可以运行在JVM虚拟机上,同样可以编译成Javascript源码,与 java 100%兼容。我们来看下Kotlin的诞生过程:

  • 2011.6 项目公开
  • 2012.2 开源 https://github.com/JetBrains/kotlin
  • 2013.8 支持androidstudio
  • 2014.6 全新的开源web站点和域名 https://Kotlinlang.org
  • 2015.3 Eclipse插件亮相
  • 2015.4 Anko亮相
  • 2016.2 1.0正式版发布

作为目前广受欢迎的Java IDE IntelliJ 的提供商,在 Apache 许可下已经开源其Kotlin 编程语言。而恰巧我一直用的IntellJ Idea。不得不说很佩服JetBrains这家公司,不仅仅制作了最流行的Java开发工具IntelliJ IDEA,Android Studio 就是基于Intellij IDEA社区版开发的,还创建了一门自己的语言。而JetBrains却并不是一家美国的公司,而是位于捷克的布拉格。JetBrains对Kotlin的愿景:用同一种语言,桥接多平台的不同应用的端对端开发,包括全栈web应用,Android和ios客户端,嵌入式/物联网等等。

为什么需要kotlin?

  • 空类型安全
  • Lambda表达式
  • 扩展方法
  • 类型推导
  • 胜任java能做的所有事,还要更加难
  • 没有分号!!!!

Kotlin 语言本身还扩展了非常多的常用操作,像文本读写、文件夹遍历、定时器调度、流式操作集合(类似RxJava),而这些都是Java语言是没有的。同时,Kotlin 的内联高阶 Lambda、动态代理、协程等特性还可以大幅优化你的代码性能。

为什么要学习 Kotlin ?_编程语言_07

如果你是一名 Android 开发,那掌握 Kotlin 语言对你就更加重要了,在 Android P 源码、Gradle 源码与 Android Jetpack 库中都已大量使用了 Kotlin 语言。其实,Kotlin 的使用范围并不局限在 Android 开发领域,还包括服务器编程以及前端 React 应用等跨平台开发。

为什么要学习 Kotlin ?_go_08

可以说,只要是 Java 能做的事情,Kotlin 都可以做,甚至还可以做得更好。

为什么要学习 Kotlin ?_java_09

Kotlin Trends

为什么要学习 Kotlin ?_软件开发_10

​​https://www.tiobe.com/tiobe-index/​​

Kotlin is on the up and up. A recent blog by JetBrains’ Roman Elizarov explained that functional programming is on the rise.

At Google I/O 2019, Android announced that “Android will be increasingly Kotlin-first”.

Two years ago, we announced Kotlin was a supported language for Android. Our top developers loved it already, and since then, it’s amazing how fast it’s grown. Over 50% of professional Android developers now use Kotlin, it’s been one of the most-loved languages two years running on Stack Overflow, and one of the fastest-growing on GitHub in number of contributors. Many new Jetpack APIs and features will be offered first in Kotlin. If you’re starting a new project, you should write it in Kotlin.

Chet Haase, Android Developers Blog

Github 上的 Kotlin 代码库:

​​https://github.com/search?l=Kotlin&q=kotlin&type=Repositories​​

PYPL PopularitY of Programming Language

为什么要学习 Kotlin ?_人工智能_11

Programming Languages InfoQ Trends Report - October 2019

为什么要学习 Kotlin ?_编程语言_12


为什么要学习 Kotlin ?_java_13

Getting Started with Kotlin:

​​https://kotlinlang.org/docs/tutorials/getting-started.html​​

Basic Syntax

Package definition and imports

Package specification should be at the top of the source file:

package my.demo

import kotlin.text.*

// ...

It is not required to match directories and packages: source files can be placed arbitrarily in the file system.

See Packages.

Program entry point

An entry point of a Kotlin application is the ​​main​​ function.

fun main() {

println("Hello world!")

}

Target platform: JVMRunning on kotlin v. 1.4.0

Functions

Function having two ​​Int​​​ parameters with ​​Int​​ return type:

fun sum(a: Int, b: Int): Int {

return a + b

}

Target platform: JVMRunning on kotlin v. 1.4.0

Function with an expression body and inferred return type:

fun sum(a: Int, b: Int) = a + b

Target platform: JVMRunning on kotlin v. 1.4.0

Function returning no meaningful value:

fun printSum(a: Int, b: Int): Unit {

println("sum of $a and $b is ${a + b}")

}

Target platform: JVMRunning on kotlin v. 1.4.0

​Unit​​ return type can be omitted:

fun printSum(a: Int, b: Int) {

println("sum of $a and $b is ${a + b}")

}

Target platform: JVMRunning on kotlin v. 1.4.0

See Functions.

Variables

Read-only local variables are defined using the keyword ​​val​​. They can be assigned a value only once.

val a: Int = 1  // immediate assignment

val b = 2   // `Int` type is inferred

val c: Int  // Type required when no initializer is provided

c = 3       // deferred assignment

Target platform: JVMRunning on kotlin v. 1.4.0

Variables that can be reassigned use the ​​var​​ keyword:

var x = 5 // `Int` type is inferred

x += 1

Target platform: JVMRunning on kotlin v. 1.4.0

Top-level variables:

val PI = 3.14

var x = 0

fun incrementX() {

x += 1

}

Target platform: JVMRunning on kotlin v. 1.4.0

See also Properties And Fields.

Comments

Just like most modern languages, Kotlin supports single-line (or end-of-line) and multi-line (block) comments.

// This is an end-of-line comment

/* This is a block comment

on multiple lines. */

Block comments in Kotlin can be nested.

/* The comment starts here

/* contains a nested comment */

and ends here. */

See Documenting Kotlin Code for information on the documentation comment syntax.

String templates

var a = 1

// simple name in template:

val s1 = "a is $a"

a = 2

// arbitrary expression in template:

val s2 = "${s1.replace("is", "was")}, but now is $a"

Target platform: JVMRunning on kotlin v. 1.4.0

See String templates for details.

Conditional expressions

fun maxOf(a: Int, b: Int): Int {

if (a > b) {

return a

} else {

return b

}

}

Target platform: JVMRunning on kotlin v. 1.4.0

In Kotlin, if can also be used as an expression:

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

Target platform: JVMRunning on kotlin v. 1.4.0

See if-expressions.

Nullable values and null checks

A reference must be explicitly marked as nullable when null value is possible.

Return null if ​​str​​ does not hold an integer:

fun parseInt(str: String): Int? {

// ...

}

Use a function returning nullable value:

fun printProduct(arg1: String, arg2: String) {

val x = parseInt(arg1)

val y = parseInt(arg2)

// Using `x * y` yields error because they may hold nulls.

if (x != null && y != null) {

// x and y are automatically cast to non-nullable after null check

println(x * y)

}

else {

println("'$arg1' or '$arg2' is not a number")

}

}

Target platform: JVMRunning on kotlin v. 1.4.0

or

// ...

if (x == null) {

println("Wrong number format in arg1: '$arg1'")

return

}

if (y == null) {

println("Wrong number format in arg2: '$arg2'")

return

}

// x and y are automatically cast to non-nullable after null check

println(x * y)

Target platform: JVMRunning on kotlin v. 1.4.0

See Null-safety.

Type checks and automatic casts

The is operator checks if an expression is an instance of a type. If an immutable local variable or property is checked for a specific type, there's no need to cast it explicitly:

fun getStringLength(obj: Any): Int? {

if (obj is String) {

// `obj` is automatically cast to `String` in this branch

return obj.length

}

// `obj` is still of type `Any` outside of the type-checked branch

return null

}

Target platform: JVMRunning on kotlin v. 1.4.0

or

fun getStringLength(obj: Any): Int? {

if (obj !is String) return null

// `obj` is automatically cast to `String` in this branch

return obj.length

}

Target platform: JVMRunning on kotlin v. 1.4.0

or even

fun getStringLength(obj: Any): Int? {

// `obj` is automatically cast to `String` on the right-hand side of `&&`

if (obj is String && obj.length > 0) {

return obj.length

}

return null

}

Target platform: JVMRunning on kotlin v. 1.4.0

See Classes and Type casts.

for loop

val items = listOf("apple", "banana", "kiwifruit")

for (item in items) {

println(item)

}

Target platform: JVMRunning on kotlin v. 1.4.0

or

val items = listOf("apple", "banana", "kiwifruit")

for (index in items.indices) {

println("item at $index is ${items[index]}")

}

Target platform: JVMRunning on kotlin v. 1.4.0

See for loop.

while loop

val items = listOf("apple", "banana", "kiwifruit")

var index = 0

while (index < items.size) {

println("item at $index is ${items[index]}")

index++

}

Target platform: JVMRunning on kotlin v. 1.4.0

See while loop.

when expression

fun describe(obj: Any): String =

when (obj) {

1          -> "One"

"Hello"    -> "Greeting"

is Long    -> "Long"

!is String -> "Not a string"

else       -> "Unknown"

}

Target platform: JVMRunning on kotlin v. 1.4.0

See when expression.

Ranges

Check if a number is within a range using in operator:

val x = 10

val y = 9

if (x in 1..y+1) {

println("fits in range")

}

Target platform: JVMRunning on kotlin v. 1.4.0

Check if a number is out of range:

val list = listOf("a", "b", "c")

if (-1 !in 0..list.lastIndex) {

println("-1 is out of range")

}

if (list.size !in list.indices) {

println("list size is out of valid list indices range, too")

}

Target platform: JVMRunning on kotlin v. 1.4.0

Iterating over a range:

for (x in 1..5) {

print(x)

}

Target platform: JVMRunning on kotlin v. 1.4.0

or over a progression:

for (x in 1..10 step 2) {

print(x)

}

println()

for (x in 9 downTo 0 step 3) {

print(x)

}

Target platform: JVMRunning on kotlin v. 1.4.0

See Ranges.

Collections

Iterating over a collection:

for (item in items) {

println(item)

}

Target platform: JVMRunning on kotlin v. 1.4.0

Checking if a collection contains an object using in operator:

when {

"orange" in items -> println("juicy")

"apple" in items -> println("apple is fine too")

}

Target platform: JVMRunning on kotlin v. 1.4.0

Using lambda expressions to filter and map collections:

val fruits = listOf("banana", "avocado", "apple", "kiwifruit")

fruits

.filter { it.startsWith("a") }

.sortedBy { it }

.map { it.toUpperCase() }

.forEach { println(it) }

Target platform: JVMRunning on kotlin v. 1.4.0

See Collections overview.

Creating basic classes and their instances

val rectangle = Rectangle(5.0, 2.0)

val triangle = Triangle(3.0, 4.0, 5.0)

Target platform: JVMRunning on kotlin v. 1.4.0

See classes and objects and instances.

​​https://kotlinlang.org/docs/reference/basic-syntax.html​​

Kotlin 设计 logo集锦


为什么要学习 Kotlin ?_java_14

为什么要学习 Kotlin ?_人工智能_15

为什么要学习 Kotlin ?_人工智能_16

为什么要学习 Kotlin ?_人工智能_17

为什么要学习 Kotlin ?_编程语言_18

为什么要学习 Kotlin ?_软件开发_19

为什么要学习 Kotlin ?_软件开发_19

为什么要学习 Kotlin ?_编程语言_18

为什么要学习 Kotlin ?_人工智能_22

为什么要学习 Kotlin ?_java_23

为什么要学习 Kotlin ?_人工智能_24

为什么要学习 Kotlin ?_go_25

为什么要学习 Kotlin ?_go_26

为什么要学习 Kotlin ?_java_27

为什么要学习 Kotlin ?_编程语言_28

为什么要学习 Kotlin ?_人工智能_29

为什么要学习 Kotlin ?_编程语言_30

为什么要学习 Kotlin ?_go_31

为什么要学习 Kotlin ?_java_32

为什么要学习 Kotlin ?_java_33

为什么要学习 Kotlin ?_编程语言_34

为什么要学习 Kotlin ?_java_35

为什么要学习 Kotlin ?_人工智能_36

为什么要学习 Kotlin ?_人工智能_37

为什么要学习 Kotlin ?_编程语言_38

为什么要学习 Kotlin ?_人工智能_39

为什么要学习 Kotlin ?_go_40

为什么要学习 Kotlin ?_java_41


举报

相关推荐

0 条评论