Eclipse下安装: eclipse安装kotlin
如果用Help->Eclipse marketplace安装不成功的话,可以用Help->Install new software
Android studio只要安装3.0版本就可以: Android studio下载
个人觉得学习kotlin语法的话,用eclipse可能比较方便点,直接写直接运行。
1. package
1
2
|
package
my.demo
import
java.util.*
|
2. 函数定义
fun函数有两个Int参数和一个Int返回值
1
2
3
|
fun sum(a: Int, b: Int): Int{
return
a + b
}
|
函数表达式和返回值
1
|
fun sum(a:Int, b: Int) = a + b
|
Unit 函数无返回值
1
2
3
|
fun sum(a: Int, b: Int):Unit {
println(
"a: ${a} , b: ${b}"
)
}
|
无返回值函数
1
2
3
|
fun sum1(a: Int, b: Int){
println(
"aa: ${a}, bb: ${b}"
)
}
|
3. 局部变量
不可变局部变量(val)
1
2
|
val a: Int =
1
// immediate assignment
val b =
2
// `Int` type is inferred
|
可变局部变量
1
2
|
var x =
5
x +=
1
|
4. 注释
// 和 /**/
5. String 模板
1
2
3
4
5
|
var a =
1
val s1 =
"a is ${a}"
a =
2
val s2 =
"${s1.replace("
is
", "
was
")}, but now is ${a}"
|
6. 条件表达式
1
2
3
4
5
6
7
|
fun maxOf(a: Int, b: Int): Int{
if
(a > b) {
return
a
}
else
{
return
b
}
}
|
使用if表达式
1
|
fun maxOf(a:Int, b: Int) =
if
(a > b) a
else
b
|
7. 使用可为null的值和null检查
一个引用必须被明确标记为可能为null
1
2
3
4
|
fun maxOf(a:Int, b: Int): Int? {
println(
"a: ${a}"
)
return
null
}
|
8. 类型检查和动态转换
1
2
3
4
5
6
7
|
fun getStringLength(obj: Any): Int? {
if
(obj is String) {
return
obj.length
}
return
null
}
|
9. 循环
1
2
3
4
5
6
7
8
9
10
11
12
13
|
val items = listOf(
"a"
,
"b"
,
"c"
,
"e"
)
for
(zz in items) {
println(zz)
}
//或者
val items = listOf(
"a"
,
"b"
,
"c"
,
"e"
,
"f"
)
for
(idx in items.indices) {
println(items.get(idx))
println(
"value: ${items[idx]}"
)
}
|
10. while 循环
1
2
3
4
5
6
7
8
|
val items = listOf(
"a"
,
"b"
,
"c"
,
"e"
,
"f"
)
var ind =
0
while
(ind < items.size) {
println(
"value: ${items[ind]}"
)
ind ++;
}
|
11. when 表达式
1
2
3
4
5
6
|
fun descrbe(obj: Any): String =
when (obj) {
1
->
"one"
"Hello"
->
"greeting"
else
->
"else default"
}
|
12. 范围
检查一个数字是否在一个范围时可以使用in
1
2
3
4
5
6
7
8
|
val x =
10
val y =
8
if
(x in
1
.. y+
1
) {
println(
"x in..."
)
}
else
{
println(
"not in"
)
}
|
检查一个数字不在一个范围
1
2
3
4
5
|
if
(x !in
1
..y+
1
) {
println(
"b not in "
)
}
else
{
println(
"b x in"
)
}
|
迭代一个范围
1
2
3
|
for
(x in
1
..
5
) {
println(x)
}
|
级数遍历一个范围
1
2
3
|
for
(x in
1
..
5
step
2
) {
println(x)
}
|
13. 使用集合
遍历
1
2
3
4
|
var lists = listOf(
"a"
,
"b"
,
"c"
)
for
(ele in lists){
println(ele)
}
|
使用in检查某个元素是否在某个集合
1
2
3
4
|
when {
"a"
in lists -> println(
"a in list"
)
"b"
in lists -> println(
"b in list"
)
}
|
使用lambda语法过滤集合
1
2
3
4
5
6
|
var lists = listOf(
"acake"
,
"apple"
,
"orange"
)
lists.filter { x->x.startsWith(
"a"
) }
.sortedBy { it }
.map { x->x.toUpperCase() }
.forEach{println(it)}
|
本文转自rongwei84n 51CTO博客,原文链接:http://blog.51cto.com/483181/1931412,如需转载请自行联系原作者