Kotlin 基本语法

常量 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
}

 

转载于:https://www.cnblogs.com/davesuen/p/5729961.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值