上回说到Kotlin使用的基本配置和一些基本特性,美中不足的,还差那么一丢丢姿势。
本次罗列一下基本姿势。最终目的,只要钱给到位,什么姿势都会~
1.函数
Kotlin中函数基本示意图:
image.png
eg.
fun testFucntion(a: Int,b: Int): Int {
return if (a > b) a else b
}
println(testFucntion(1, 2))
注:与Java相比,每句话结束并不需要分号;
2. 变量
val name = "hello world" 【常量,相当于JAVA中的final修饰符】
val age = 12 【等价于 val age: Int = 12,常量age】
var age= 12 【变量 age】
注:val用于声明常量,var用于声明变量
3.类和属性
在JAVA中的写法
/* Java */
public class Person {
private final String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
在Kotlin中的写法
/* Kotlin */
class Person(val name: String)
4.接口(Interface)
/**Kotlin*/
interface Clickable {
fun click()
}
class Button : Clickable{
override fun onClick(){
//implemented
}
}
注:Kotlin在类名后面使用一个冒号来替代Java中的 extends 和 implements 关键词。
5.数组
先看Java中数组的声明:
String[] colors = new String[]{"Red", "Green", "Yellow"};
String[] emptyStrings = new String[7];
在kotlin中数组的声明:
val names: Array = arrayOf("Red", "Green", "Yellow")
val emptyStrings: Array = arrayOfNulls(7)
6.可变参数
/** JAVA */
void function(String... parameters){
...
}
/**Kotlin*/可变参数( Varargs) : 可以接受任意个参数的函数
void function(vararg parameters : String){
...
}
7.实例化
/**JAVA*/
Date date = new Date();
/**Kotlin*/告别new
val date = Date()
8.Lambda表达式
Lambda作为方法参数的代码块
以JAVA代码示例:
/* Java */
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
/* actions on click */
}
});
/**Kotlin*/
button.setOnClickListener { /* actions on click */ }
Lambda与集合
val people = listOf(Person("Alice", 29), Person("Bob", 31))
println(people.maxBy { it.age }) // 通过比较年龄找出最大值
注:maxBy函数可以在任何集合中被调用,而它只需要一个参数:指定什么样的值应该进行比较来找到最大值元素的函数。大括号中的代码 { it.age } 是一个实现这样的逻辑的lambda。
Lambda表达式语法
image.png
val sum = { x: Int, y: Int -> x + y }
println(sum(1, 2))
forEach中的Lambda
fun printMessageWithPrefix(messages: Collection,
error: String) {
messages.forEach {
print("$error$it")
}
}
testLambda(){
val listOf = listOf("403 Forbidde","404 Not found")
printMessageWithPrefix(listOf,"error")
}
9.集合函数式API
filter
filter 函数变换一个集合,并过滤出不满足给定断言的元素:
val list = listOf(1, 2, 3, 4)
list.filter { it % 2 == 0 }
>>[2, 4]
map
map 函数对集合中的每个元素应用给定的函数,并且收集结果形成新的集合
val list = listOf(1, 2, 3, 4)
list.map { it * it }
>>[1, 4, 9, 16]
filter和map共用
people.filter { it.age > 30 }.map(Person::name)
groupBy
val people = listOf(Person("Alice", 31),
...
Person("Bob", 29), Person("Carol", 31))
>>println(people.groupBy { it.age })
一个映射通过键被分成多个组