首页 > 其他 > 详细

Kotlin 基本语法

时间:2016-08-02 18:52:30      阅读:212      评论:0      收藏:0      [点我收藏+]

常量 val a: Int = 5

变量 var a: Int = 5

Any:匹配任何类型

:nullable,比如 a?.toString,如果 a 为 null 不会出错。

函数基本结构

fun copyAddress(address: Address): Address {
  val result = Address() // there‘s no ‘new‘ keyword in Kotlin
  result.name = address.name // accessors are called
  result.street = address.street
  // ...
  return result
}

1. 函数名,参数,返回类型
fun sum(a: Int, b: Int): Int { 
  return a + b
}

2. 函数名,参数,返回值
fun sum(a: Int, b: Int) = a + b

3. 函数名,参数,无返回值
fun printSum(a: Int, b: Int) {
  print(a + b)
}
无返回值可以用 Unit 表示

 

String 字符串中可以加参数

print("First argument: ${array[0]}")

 

if

val max = if (a > b) { 
    print("Choose a") 
    a 
  } 
  else { 
    print("Choose b") 
    b 
  }

fun max(aIntbIntif (belse b

 

when (switch in Java)

when (x) {
  1 -> print("x == 1")
  2 -> print("x == 2")
  else -> { // Note the block
    print("x is neither 1 nor 2")
  }
}

 

类型转换 (cast)

fun getStringLength(obj: Any): Int? {
  if (obj is String) {
    // `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
}

 

Kotlin 基本语法

原文:http://www.cnblogs.com/davesuen/p/5729961.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!