Kotlin简介与入门

Kotlin是一个基于 JVM 的编程语言,由 JetBrains 开发。Kotlin可以编译成Java字节码,也可以编译成JavaScript,方便在没有JVM的设备上运行。

在 Google I/O 2017 大会上,Google 宣布 Android Studio 3.0 完全支持 Kotlin,称其“简洁、表现力强,具有类型安全和空值安全的特点,也可以与java进行完整的互操作”。

下面简单介绍kotlin语法并与java对比语法差异。

1.赋值表示

变量:var varNumber=1(隐式类型推断)

常量:val constantNumber=1(隐式类型推断)

var str:String?="abc"(显示类型表示)

var other:String?

other=null

2.流控制

if表达式:

// 传统用法

var max=a

if (a<b) max=b

//表达式用法

val max = if (a>b) a else b

//如果分支是块,那么最后一个表达式是块的值

val max = if ( a > b ) {

      print("choose a")

      a

} else  {

      print("choose b")

      b

}

when表达式:

when代替了c风格的switch语句:

when (x) { 

         1 -> print("x == 1") 

         2 -> print("x == 2") 

         else -> { // Note the block 

                print("x is neither 1 nor 2") 

          }

}

如果许多情况需要以同样的方式处理,分支情况可以用逗号结合起来:

when (x) { 

         0, 1 -> print("x == 0 or x == 1") 

         else -> print("otherwise") 

}

可以用任意表达式当做分支语句:

when (x) { 

        parseInt(s) -> print("s encodes x") 

        else -> print("s does not encode x") 

}

我们也可以检测一个值是不是在一个范围或集合中:

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") 

}

for循环:

语法表示:

for (item in collection) print(item)

迭代数组或集合下标:

for (i in array.indices) {

      print(array[i])

 }

遍历下标,值元组:

for ((index, value) in array.withIndex()) { 

      println("the element at $index is $value")

 }

while循环:

while (x > 0) {

     x--

}

do {

    val y = retrieveData() 

} while (y != null)  //注意此处y可见

3.函数

用fun关键字声明函数,函数声明采用Pascal命名法,即name:value形式:

fun double(x: Int): Int { }

参数可以有默认值:

fun read(b: Array, off: Int = 0, len: Int = b.size()) { 

...

}

Unit代表无返回值函数:

fun printHello(name: String?): Unit { 

     if (name != null) println("Hello ${name}") 

    else println("Hi there!") 

}

4.Lambda表达式与匿名函数

lambda语法:

val sum = { x: Int, y: Int -> x + y }

ints.filter { it > 0 }

匿名函数:

fun(x: Int, y: Int): Int = x + y

5.Java与kotlin对比

打印:

//Java

System.out.print("Amit Shekhar");

System.out.println("Amit Shekhar");

//kotlin

print("Amit Shekhar")

println("Amit Shekhar")

空值检查:

//Java

if(text!=null){

    int length=text.length();

}

//kotlin

text?.let {

    val length=text.length

}

实例判断与转换:

//Java

if (object instanceof Car){

    Car  car=(Car) object;

}

//kotlin

if (objectisCar) {

    var car=object //smartcasting

}


参考链接:

1.http://kotlinlang.org/docs/kotlin-docs.pdf

2.https://github.com/MindorksOpenSource/from-java-to-kotlin/blob/master/README.md

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容