Kotlin 学习笔记(二)—— 基础语法

Kotlin 学习笔记(二)—— 基础语法


Kotlin学习笔记系列教程

Kotlin 学习笔记(一)—— 概述、学习曲线、开发工具、参考资料


1. 基础语法

定义包

包的声明应该处于源文件顶部:

package hard.uistudy.dai.uifinaltest.main.view.fragment

import android.os.Bundle
import android.support.v4.app.Fragment
定义函数

带有两个Int 参数、返回Int 的函数:

    fun addNumber(a : Int, b: Int) : Int {
        return a + b
    }

将表达式作为函数体、返回值类型自动推断的函数:

fun addNumber(a: Int, b: Int) = a + b

函数返回无意义的值:

fun printSum(a: Int, b: Int): Unit {
    println("sum of $a and $b is ${a + b}")
}

Unit 返回类型可以省略:

fun printSum(a: Int, b: Int) {
    println("sum of $a and $b is ${a + b}")
}
定义变量

一次赋值(只读不可写)的局部变量,使用val修饰:

    val a : Int =5  //立即赋值
    val text  = "aaa"  //自动推断类型

可变变量(可读可写),使用var修饰:

    var b = 5 // 自动推断出 `Int` 类型
    b = 6

    /**
     * 定义暂不赋值,lateinit不能用在可空的属性上和java的基本类型上,lateinit只能修饰var
     */
    lateinit var open : String
    ...
    open = "aaa"
  ```

  顶层变量:
  ```
  val PI = 3.14
var x = 0

fun incrementX() { 
    x += 1 
}
注释

同Java一样,kotlin也支持行注释 及 块注释

// 这是一个行注释

/* 这是一个多行的
   块注释。 */
使用字符串模板

使用$符号

var a = 1
// 模板中的简单名称:
val s1 = "a is $a" 

a = 2
// 模板中的任意表达式:
val s2 = "${s1.replace("is", "was")}, but now is $a"
使用条件表达式
fun maxOf(a: Int, b: Int): Int {
    if (a > b) {
        return a
    } else {
        return b
    }
}

使用 if 作为表达式:

fun maxOf(a: Int, b: Int) = if (a > b) a else b
使用可空值及 null 检测

当某个变量的值可能为null时,必须在声明处的类型后添加?来标识该引用可为空。
如果text的内容不是数字返回null:

    fun parseInt(string: String) : Int?{
      return  if (string.toInt() != null) string.toInt() else null
    }

使用返回可空值的函数:

    fun  getProduct(str1: String, str2: String){
        val x = parseInt(str1)
        val y = parseInt(str2)

        if (x != null && y != null){
            print(x + y)
        } else{
            println("either '$str1' or '$str2' is not a number")
        }

    }

或者 分别分析

// ……
if (x == null) {
    println("Wrong number format in arg1: '$arg1'")
    return
}
if (y == null) {
    println("Wrong number format in arg2: '$arg2'")
    return
}

// 在空检测后,x 和 y 会自动转换为非空值
println(x * y)
使用类型检测及自动类型转换

is 运算符检测一个表达式是否为某类型的一个实例。如果一个不可变的局部变量或者属性已经判断出为某类型,那么检测后的 分支直接当做该类型使用,无需显示转换:

    fun getStrigLength(obj:Any): Int?{
        if (obj is String){
            // `obj` 在该条件分支内自动转换成 `String`
            return obj.length
        }
        // 在离开类型检测分支后,`obj` 仍然是 `Any` 类型
        return null
    }

或者

fun getStringLength(obj: Any): Int? {
    if (obj !is String) return null// `obj` 在这一分支自动转换为 `String`
    return obj.length
}

甚至

fun getStringLength(obj: Any): Int? {
    // `obj` `&&` 右边自动转换成 `String` 类型
    if (obj is String && obj.length > 0) {
        return obj.length
    }
​
    return null
}
使用 for 循环
    val list  = arrayListOf("1","2","3","4")

    fun printList(){
        for (item in list){
            print(item)
        }
    }

或者

    val list  = arrayListOf("1","2","3","4")

    fun printList(){
        for (index in list.indices){
            print("$list at $index value is ${list[index]} " )
        }
    }
使用While循环
    val list  = arrayListOf("1","2","3","4")

    fun printList(){
        var index = 0
       while (index < list.size){
           print("$index,${list[index]}")
           index++
       }
    }
使用When循环
    fun printList(index : Int) : String =
        when (index ){
            1 -> "$index value is 1"
            2 -> "$index value is 2"
            3 -> "$index value is 3"
            4 -> "$index value is 4"
            else  -> "null"
        }
使用区间(range)

使用 in 运算符来检测某个数字是否在指定区间内:

    val startIndex = 10
    val endIndex = 20

    fun sortNum(){
        if (startIndex in 1.. endIndex){
            print("$startIndex is in range")
        }
    }

区间迭代:

    fun sortNum(){
        for (index in startIndex .. endIndex){
            print(index)
        }
    }

数列迭代

        //每次跳过3个元素
        for (index in startIndex .. endIndex step 3){
            print(index)
        }

        //降序遍历,每次跳过3个元素
        for (index in endIndex downTo startIndex step 3){

        }

检测某个数字是否在指定区间外:

val list = listOf("a", "b", "c")

if (-1 !in 0..list.lastIndex) {
    println("-1 is out of range")
}
if (list.size !in list.indices) {
    println("list size is out of valid list indices range too")
}
val list = listOf("a", "b", "c")
​
if (-1 !in 0..list.lastIndex) {
    println("-1 is out of range")
}
if (list.size !in list.indices) {
    println("list size is out of valid list indices range too")
}
使用集合

对集合进行迭代:

    val lists = listOf("a", "b", "c")

    fun sortList(){
        for (item in lists){
            print(item)
        }
    }

使用in 运算符来判断集合内是否包含某实例:

    val lists = listOf("a", "b", "c")

    fun sortList(){
        when{
            "a" in lists -> print("a")
            "b" in lists -> print("b")
        }
    }

使用lambda 表达式来过滤(filter)和映射(map)集合:

    val lists = listOf("aa", "ab", "ac","1","2","3","4")

    fun sortList(){
       lists.filter { it.startsWith("a")}  //过滤出 a 开头的元素
               .sortedBy { it }   //排序
               .map { it.toUpperCase() }  //将字符串转为大写
               .forEach { print(it) }  //遍历输出字符串
    }
创建基本类及其实例
    val rectangele = Rectangle()  //不需要 new 关键字
    val triangle = Triangle()

以上就是第二篇的全部内容,先学习到这里,第三篇继续学习基础教程


个人博客地址:http://outofmemory.top/
CSDN地址:http://blog.csdn.net/dazhaoDai
GitHub地址:https://github.com/dazhaoDai


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值