Kotlin 基本语法
2017-06-28 16:55
603 查看
定义包
package com.demo
定义方式和Java一样,没什么区别
import java.util.*
导入类也是一样
函数定义
定义sum函数,有Int两个参数,返回Intfun sum(a: Int, b: Int): Int { return a + b }
疯狂写法(表达式)
fun sum(a: Int, b: Int)=a+b
有两个参数,没有返回
fun printSum(a: Int, b: Int): Unit { println("sum of $a and $b is ${a + b}") }
Unit关键字和java的void一样效果
当然也可以这样写:
fun printSum(a: Int, b: Int) { println("sum of $a and $b is ${a + b}") }
定义变量
不变变量,如果尝试更改,则会报错fun main() { val a: Int = 1 // val b = 2 // `Int` 自动判断类型 val c: Int // 当没设置初始值的时候,需要写类型 c = 3 // 自动判断类型 println("a = $a, b = $b, c = $c") }
可变变量(可更改变量)
var a=5 x+=1
注释
// 我是注释 /*我是注释2*/
字符串模板
var a = 1 //定义模板 val s1 = "a is $a" a = 2 //使用模板进行替换 val s2 = "${s1.replace("is", "was")}, but now is $a" println(s2)
条件语句
fun maxOf(a: Int, b: Int): Int { if (a > b) { return a } else { return b } }
使用表达式:
fun maxOf(a: Int, b: Int) = if (a > b) a else b
null值和null值检测
// fun parseInt(str: String): Int? { return str.toIntOrNull() } fun printProduct(arg1: String, arg2: String) { val x = parseInt(arg1) val y = parseInt(arg2) // 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 println(x * y) } else { println("either '$arg1' or '$arg2' is not a number") } }
类型检查和自动转型
fun getStringLength(obj: Any): Int? { if (obj is String) { // 自动转型 return obj.length } return null }
for 循环
fun forLoop(){ val items = listOf("aa", "bb", "cc"); for (item in items) { println(item); } for (index in items.indices) { println("item at $index is $items[index]"); } }
while 循环
fun whileLoop(): Unit { val whiles = listOf("app", "bana", "kk"); var index = 0 while (index < whiles.size) { println("item at $index is ${whiles[index]}"); index++; } }
when 表达式
fun whenExpression(obj: Any): String = when (obj) { 1 -> "One" "hello" -> "Greeting" is Long -> "Long" is String -> "String" else -> "unknown" }
使用范围(ranges)
fun useRanges(): Unit { val x = 10 val y = 9 if (x in 1..y + 1) { println("fits in range") } // if (-1 !in 0..y - 1) { println("-1 not in range") } // for (x in 1..5) { print(x) } // for (xx in 1..10 step 2) { print(xx); } }
使用集合
fun useCollections(): Unit { val items = setOf("apple", "banana", "kiwi") when { "orange" in items -> println("juicy") "apple" in items -> println("apple is fine too") } }
相关文章推荐
- Kotlin Primer·第二章·基本语法
- Kotlin——程序的基本逻辑结构之选择、循环和跳转基本语法
- Kotlin_01基本语法
- Kotlin的基本语法和类型
- kotlin基本语法与类型
- Kotlin 开发Android :基本语法
- Kotlin基本语法
- Kotlin Primer·第二章·基本语法
- Kotlin 学习笔记(1)基本语法
- Kotlin——基本语法
- Kotlin基本语法(一)
- Kotlin Primer·第二章·基本语法
- Kotlin基本语法
- kotlin 基本语法(五)
- kotlin 学习记录 基本语法(1)
- Kotlin Primer·第二章·基本语法
- Kotlin基础(一Kotlin基本语法)
- Kotlin VS Java:基本语法差异
- Kotlin开发Android(2): Kotlin声明变量常量方法等基本语法
- Kotlin属性和字段与基本语法