实在是扛不住Kotlin席卷之势,连我的老大也说以后有机会就尝试一下用Kotlin。果然有了谷爹的撑腰就是牛掰哄哄,吓得我这渣渣赶紧开启学习模式。
这或许是小弟第一次的系列博客(希望不是三分钟热血…),写博客的主要目的是记录学习过程,免得第二天睡醒又忘了。
小弟的学习资源就是Kotlin官网,不用梯子就可以看哦
突突突…开车了…
Kotlin是这样定义方法(翻译为函数好像更准确…anywhere)的:
fun sum(a: Int, b: Int): Int {
return a + b
}
这段代码翻译为 java是这样的:
public int sum(int a,int b){
return a + b;
}
恩恩,有了这么直观的对比,应该就无需多加解释了哈(其实是我懒)
Kotlin可以根据函数里的参数类型推测函数的返回类型:
fun sum(a: Int, b: Int) = a + b
用起来的效果是这样的:
fun main(args: Array<String>) {
println("sum of 19 and 23 is ${sum(19, 23)}")
}
sum of 19 and 23 is 42,是的Kotlin还支持类似 JavaScript的 $占位符操作
这样写的话,sum返回的类型也是 Int, 翻译为java大概是这样的:
public int sum(int a,int b){
return a + b;
}
int c = sum(a + b);
Kotlin的函数可以返回一个无意义的值(官网原文是Function returning no meaningful value)
fun printSum(a: Int, b: Int): Unit {
println("sum of $a and $b is ${a + b}")
}
可以把Unit省略
fun printSum(a: Int, b: Int) {
println("sum of $a and $b is ${a + b}")
}
翻译为java大概是这样的:
public void printSum(int a, int b){
println("sum of "+ a + "and"+ b +"is"+ (a + b));
}
这个翻译并不准确,因为java的void是没有返回值的,而Kotlin的Unit却有返回值,只是返回值 no meaningful(无意义)。
再来看看Kotlin是怎样定义变量的:
val a: Int = 1 // immediate assignment(声明后立刻赋值)
val b = 2 // `Int` type is inferred(推测b是Int类型)
val c: Int // Type required when no initializer is provided(当声明的变量没有立刻赋值,需要为变量指明类型)
c = 3 // deferred assignment(使用时赋值(直译是延迟赋值))
/********************************/
var x = 5 // `Int` type is inferred(x被推测为Int类型)
x += 1
可以看到声明变量有两个不同的关键字,val 和 var,声明为val的变量是不可变的,相当于java里的final,而声明为var的变量则是可变的。跟JavaScript一样,所有的变量都是用val或者var关键字声明( JavaScript好像直有var)
再来看看Kotlin的if语句:
fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}
其实跟java的if-else是一样一样的…
Kotlin号称的nullpointer检测,其实是这样实现的:
fun parseInt(str: String): Int? {
// ...省略String to Int的转换代码
//Return null if str does not hold an integer
//当str不是integer类型的时候,函数将返回null
}
测试代码:
fun parseInt(str: String): Int? {
return str.toIntOrNull() //这是Kotlin的Api
}
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 nullcheck
println(x * y)
}
else {
println("either '$arg1' or '$arg2' is not a number")
}
}
/**********************测试代码********************************/
fun main(args: Array<String>) {
printProduct("6", "7")
printProduct("a", "7")
printProduct("a", "b")
}
/*********************运行结果********************************/
42
either 'a' or '7' is not a number
either 'a' or 'b' is not a number
没错,就是在返回类型 Int后面加上一个 ? 就表示函数有可能是返回null
Kotlin的变量类型检查:
fun getStringLength(obj: Any): Int? {
if (obj is String) { //is相当于java里的instance of
// `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
}
/***************测试代码********************/
fun main(args: Array<String>) {
fun printLength(obj: Any) {
println("'$obj' string length is ${getStringLength(obj) ?: "... err, not a string"} ")
}
printLength("Incomprehensibilities")
printLength(1000)
}
/***************运行结果***********************/
'Incomprehensibilities' string length is 21
'1000' string length is ... err, not a string
Kotlin的for循环和while循环(其实跟java的差不多…)
val items = listOf("apple", "banana", "kiwi")//listOf是声明数组,以后再细说
for (item in items) { //in就相当于java for循环中的 : 符号
println(item)
}
/***********************************************/
for (x in 1..5) { //从1到5迭代
print(x)
}
/***********************************************/
fun main(args: Array<String>) {
for (x in 1..10 step 2) { //翻译成java是这样的:
print(x) //for(int x=1;x<=10;x +=2){
} // print(x)
// }
for (x in 9 downTo 0 step 3) { //翻译成java是这样的:
print(x) //for(int x=9;x>=0;x -=3){
// print(x)
} // }
//
/***********************************************/
val items = listOf("apple", "banana", "kiwi")
var index = 0
while (index < items.size) {
println("item at $index is ${items[index]}")
index++
}
不一样的when表达式(其实就是java里的siwtch-case,只是when屌了很多…):
fun describe(obj: Any): String =
when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}
/**********************测试代码*******************/
fun main(args: Array<String>) {
println(describe(1))
println(describe("Hello"))
println(describe(1000L))
println(describe(2))
println(describe("other"))
}
/**********************运行结果***********************/
One
Greeting
Long
Not a string
Unknown
翻译成java是这样的:
public String describe(String str){
switch(str){ //java8支持了对String的switch操作
case "1":
"One";
break;
.
.
.
default:
"Unknown"
break;
}
}
Kotlin的基本语法就介绍到这里了……该睡觉了…..