Kotlin 基础语法学习

  Kotlin 基础语法学习 

定义包名

基础语法
定义包名

包名的定义应当在源文件的头部

package my.demo

import java.util.*
// ...
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

文件路径和包名并不要求匹配,源文件可以被放置在文件系统任意位置

参考:

定义函数

函数有两个Int类型参数和Int类型返回值:

fun sum(a: Int, b: Int): Int {
  return a + b
}
 
 
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

函数体中只有一个表达式并且作为函数的返回值:

fun sum(a: Int, b: Int) = a + b
 
 
  • 1
  • 1

函数没有返回值:

fun printSum(a: Int, b: Int): Unit {
  print(a + b)
}
 
 
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

Unit类型的返回值类型可以省略:

fun printSum(a: Int, b: Int) {
  print(a + b)
}
 
 
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

参见:函数

定义局部变量

定义只读类型的局部变量:

val a: Int = 1
val b = 1   // `Int` 类型是被编译器推理出
val c: Int  // 当变量的初始值没有被提供时,需要定义变量的类型
c = 1       // 赋值
 
 
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

可变局部变量

var x = 5 // `Int` 类型是被编译器推理出的
x += 1
 
 
  • 1
  • 2
  • 1
  • 2

可参见:属性与变量

就像Java与JavaScripe,Kotlin也支持行注释与代码块注释。

// 这是一段行注释

/* 这是一段代码块
    注释 */
 
 
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

不像Java,代码块注释在Kotlin中是可以被叠加的。

参见:Kotlin文档代码

使用字符串模板
fun main(args: Array<String>) {
  if (args.size == 0) return

  print("First argument: ${args[0]}")
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

参见:字符串模板

使用条件表达式
fun max(a: Int, b: Int): Int {
  if (a > b)
    return a
  else
    return b
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

使用 if 作为一个表达式返回值:

fun max(a: Int, b: Int) = if (a > b) a else b
 
 
  • 1
  • 1

参见:if表达式

使用可空变量并检测是否为空

一个引用必须明确的被设置为可为空当其可能为空值时。

返回值为null 如果str 没有包含数值:

fun parseInt(str: String): Int? {
  // ...
}
 
 
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

函数的返回值可能为空:

fun main(args: Array<String>) {
  if (args.size < 2) {
    print("Two integers expected")
    return
  }

  val x = parseInt(args[0])
  val y = parseInt(args[1])

  // 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 null check
    print(x * y)
  }
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

或者:

// ...
  if (x == null) {
    print("Wrong number format in '${args[0]}'")
    return
  }
  if (y == null) {
    print("Wrong number format in '${args[1]}'")
    return
  }

  // x and y are automatically cast to non-nullable after null check
  print(x * y)
  转载自:http://blog.csdn.net/qq_23547831/article/details/52923248   
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值