丙午🐎年

acc8226 的博客

此样式指南与您可能看到的其他样式指南不同,因为重点是以印刷和网络的可读性为中心。我们创建了这个风格指南,以使我们教程中的代码保持一致。

Our overarching goals are conciseness, readability and simplicity.

You should also check out out Swift
and Objective-C
style guides too.

Inspiration

This style-guide is somewhat of a mash-up between the existing Java language
style guides, and a tutorial-readability focused Swift style-guide. The language
guidance is drawn from the
Android contributors style guide
and the
Google Java Style Guide.
Alterations to support additional readability in tutorials were inspired by the
raywenderlich.com Swift style guide.

阅读全文 »

函数是能完成某项特定任务的可复用代码块,是编程非常重要的一部分。事实上,程序基本上就是一系列函数的组合,用来完成较复杂的任务。

函数声明

Kotlin 中的函数很灵活,它可以独立于类或接口之外存在,不属于任何的类,即顶层函数(top-level function),也就是全局函数,之前接触的 main 函数就属于顶层函数;也可以存在于别的函数中,即局部函数;还可以存在于类或接口之中,即成员函数。

1
2
3
4
fun 函数名(参数列表) : 返回值类型 {
函数体
return 返回值
}

在参数列表后 “: 返回值类型” 指明函数的返回值类型,如果函数没有需要返回的数据,则 “: 返回值类型” 可以省略。对应地,如果函数有返回数据,就需要在函数体最后使用 return 语句将计算的数据返回。

阅读全文 »

高阶函数

高阶函数是以另一个函数作为参数 and/or 返回函数的函数。

将函数作为参数

1
2
3
4
5
6
7
8
9
10
11
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 是由 Array 类表示的。它有 get ()和 set ()函数,这些函数通过运算符重载约定转换为[] ,还有 size 属性,以及其他有用的成员函数:

1
2
3
4
5
6
7
8
class Array<T> private constructor() {
val size: Int
operator fun get(index: Int): T
operator fun set(index: Int, value: T): Unit

operator fun iterator(): Iterator<T>
// ...
}

要创建一个数组,使用函数 arrayOf ()并将条目值传递给它,以便 arrayOf (1, 2, 3)创建一个数组[1, 2, 3]。或者,可以使用 arrayOfNull ()函数创建一个给定大小的数组,其中填充 null 元素。

阅读全文 »

包

在 Kotlin 与 Java 一样为了防止类、接口、枚举、注释和函数等内容命名冲突引用了包(package)概念,包本质上命名空间(namespace)。在包中可以定义一组相关的内容(类、接口、枚举、注释和函数),并为它们提供访问保护和命名空间管理。

0%