0%

Kotlin 学习笔记 - 1

前言

Kotlin 是 Jetbrains 公司开发的语言,与 Java 具有紧密的关系,同时得到了 Google 的官方支持,目前大量的使用在 Android 开发中。因为写 APP 还是比 PC 端程序感觉上更有意思一点,所以最近开始从头学 Kotlin。(我也知道现在更应该学 Js 或者看论文或者加深计算机算法等基础 ,但是这种像打游戏一样的欲望实在是难以克制,有好多想写的 APP)

找到了很多相关的参考资料,现列举如下。

在上面的资料中,几乎哪个都试过了一点。 Udacity 是视频 + 练习,视频的连接质量很棒,内容看了一部分也很棒,但是感觉看视频总体来说学的比较慢,由于个人时间较为紧张还是偏向文字类的教程。然后有看到 Kotlin 的官网有 Kotlin Koan 系列,也就是 Kotlin 心印,是 在线的代码运行环境,搭配教程和练习,使用了一下感觉很棒,正打算使用这个学习。但是又发现说 IDEA 有 Edu 插件,可以直接在 IDE 里学习。我想了想 IDE 好歹是客户端,速度和效果上肯定会比 Web 好,于是最终投身了 IDEA + EduTools。然而这个使用的是上面最后的 HyperSkill.org 的教程,这个网站的联机质量奇差,非常非常慢……但是进去看了看,是边做项目边学,而且把知识点按树状分叉,还有前置节点等等看的超有感觉。

JetBrains Academy Knowledge Map

PS:本篇文章假设读者具有 Java 编程基础。

Related Blogs:

正文

由于已经有一些语言的编程基础,所以学 Kotlin 还是相对比较容易的,也不知道该如何将学习的过程用 Markdown 的章节式总结,就随心记下一些内容吧。

When

Kotlin 相比其他常用高级语言的第一个让我印象深刻的是 when. 但是实际上,when 感觉就是 switch 语句的升级版,写起来看上去更好看,而且支持更多操作,比如像和range 搭配。

1
2
3
4
5
6
when (x) {
in 1..10 -> print("x is in the range")
in validNumbers -> print("x is valid")
!in 10..20 -> print("x is outside the range")
else -> print("none of the above")
}

还有 when 还可以直接扔到表达式的右边。

1
2
3
4
fun hasPrefix(x: Any) = when(x) {
is String -> x.startsWith("prefix")
else -> false
}

Null 保护

这个几乎是所有 Kotlin 的教程都会提到的一点,想我之前在写基于 Java 的 Android APP 时,也经常会遇到 NullPointerException 然后程序崩掉,仔细想想好像绝大部分 App 崩溃都是因为这个错误。

然后就是 默认情况下的 变量 是不能为 Null 的,除非在声明时加一个 ? 在后面,另外在有些时候如果出现了可为 Null 和 不可以为 Null 的冲突,可以在后面加一个 !! 作为 Assertion 。 否则一旦发生冲突,在编译的时候就会报错,根本不可能跑起来。

单表达式函数

Kotlin 有时候会看见一些对于使用 C 或者 Java 的程序员来说比较陌生的函数。对于单表达式的函数,可以省略大括号,使用如下方法书写。

1
2
3
4
5
fun sum(a: Int, b: Int): Int = a + b

fun sayHello(): Unit = println("Hello")

fun isPositive(number: Int): Boolean = number > 0

类似的,返回值类型可以省略。

1
2
3
4
5
fun sum(a: Int, b: Int) = a + b // Int

fun sayHello() = println("Hello") // Unit

fun isPositive(number: Int) = number > 0 // Boolean

一些字符串函数

  • .first() returns the first symbol of the string.
  • .isEmpty() returns true, if the string has no symbols, otherwise, it returns false.
  • .drop(n) removes n first symbols from the string and returns the resulting string.
  • .reversed() returns the reversed string.
  • .toInt() converts the string to an integer and returns it.

Maven 相关

其实在这篇博客里插一条 Maven 属实有些奇怪,但是的确之前学 Java 的时候没有太理解 Maven 的角色。之后如果会有合适的博文再把这部分拿走吧。

Maven 是一个项目管理工具。提供一个统一的项目结构,描述他如何构建以及他的依赖。构建过程中,Maven 可以自动测试并报告构建情况。

Project Object Model (POM) :每个 Maven 项目都有一个 叫做 pom.XML 的文件。这里包含了类似名称,版本,属性,依赖,配置信息等细节。

https://maven.apache.org/download.cgi Maven 下载地址。

构建工具

构建工具帮助程序员构建程序,功能大致如下:

  • 下载、添加依赖项
  • 编译(源代码到字节码)
  • 打包编译后的代码(例如生成 Jar,Apk)
  • 测试
  • 部署

Java 下的 3 大构建工具。 https://hyperskill.org/learn/step/4284

There are three main build tools for Java-based projects: Apache Ant, Apache Maven, and Gradle.

Apache Ant was released in 2000. It is the oldest of these three build tools. Coders rarely use Ant in new projects but it still occurs in practice. You can use this tool together with Apache Ivy to manage dependencies.

Apache Maven was released in 2004, and now it is one of the most popular choices for Java developers (especially for server-side development). Many projects, both old and new, use Maven as a build tool because of its powerful dependency management possibilities.

Maven follows the Convention Over Configuration concept which means that a developer needs to specify only unconventional aspects of the application, and all standard aspects are to work by default.

Gradle is a new tool comparing to Ant and Maven. It was released in 2007 and is now standard for Android applications. Also, developers use it for server and desktop development. Gradle aims to “combine the power and flexibility of Ant with the dependency management and conventions of Maven into a more effective way to build.”

构造函数

Kotlin中的构造函数就叫构造函数,参照代码。

1
2
3
4
5
6
7
8
9
class Size {
var width: Int = 0
var height: Int = 0

constructor(_width: Int, _height: Int) {
width = _width
height = _height
}
}

另外关于构造函数, Kotlin 提供了许多骚操作。

1
2
3
4
5
class Size constructor(width: Int, height: Int) {
val width: Int = width
val height: Int = height
val area: Int = width * height
}
1
2
3
4
5
class Size(width: Int, height: Int) {
val width: Int = width
val height: Int = height
val area: Int = width * height
}
1
2
3
4
class Size(val width: Int, height: Int) {
val height: Int = height
val area: Int = width * height
}
1
2
3
class Size(val width: Int, val height: Int) {
val area: Int = width * height
}

是的没错,上面几种代码干的都是一个事,观察一下就可以知道在 Kotlin 中哪些部分可以省略。

单行类

1
class Size(val width: Int, val height: Int)

像是如果没有需要计算的成员变量的类则可以通过上面的代码快速声明。


其他

命名规则还是比较传统的,变量与函数均是小驼峰。

代码格式偏向 Java,大括号在上一行的行末开始,在最后一行单开一行结束,使用4个空格缩进(不可以用 Tab),最后,大多数情况下代码行末的分号可以省略,这种时候尽可能省略。

函数声明格式如下。

1
2
3
4
fun functionName(p1: Type1, p2: Type2, ...): ReturnType {
// body
return result
}

另外有些时候见到返回类型是 Unit ,就是没有返回值的意思。当然 Kotlin 建议这种时候省略返回类型部分。

1
2
3
4
5
6
/**
* The function prints the sum of a and b
*/
fun printSum(a: Int, b: Int): Unit {
println(a + b)
}

Kotlin 的 range 是闭集合,参考代码理解。

1
2
3
println(5 in 5..15)  // true
println(12 in 5..15) // true
println(15 in 5..15) // true

range 甚至可以是字符串的,这里参照字典序。

1
2
3
4
5
println('b' in 'a'..'c') // true
println('k' in 'a'..'e') // false

println("hello" in "he".."hi") // true
println("abc" in "aab".."aac") // false

相比其他语言的 while ,for, foreach 等等, Kotlin 又引入了一个 repeat。是的就是简单粗暴字面意义,repeat。

1
2
3
repeat(n) {
// statements
}

上面的代码表示将内部的代码块执行 n 次。

Kotlin 中区分字符与字符串(与python划分界限哈哈哈),字符使用 ''表示(类似C),但是一个字符占用 2 个字节空间(与 C 区别)