Kotlin学习(3):习惯用法

1、数据类
(1)创建数据类
data class Custom(val name:String,val email:String)
(2)系统自动提供的功能
  • 所有属性的getters(对于val定义还有setters)
  • equals()
  • hashCode()
  • toString()
  • copy()
  • 所有属性的component1()、component2()
2、函数默认参数

一般情况下如果函数的参数都有默认值

//下面两种方法的效果是等同的
fun foo(x: Int = 0, y: String = "") {
    println("$x is $y")
}

fun fzz(x: Int, y: String) {
    println("$x is $y")
}

fun main(args: Array<String>) {
    foo(3, "three")
    fzz(4, "four")
}
3、list的过滤

一般情况下,集合使用filter方法对数据进行过滤。

val list = listOf(1, 3, 4, 5, 6, 7, 8, 9, 10)

//两种实现方式是等同的
val positives = list.filter { x -> x > 5 }
val positives2 = list.filter { it > 5 }

fun main(args: Array<String>) {
    println(positives.forEach { print(it) })
    println(positives2.forEach { print(it) })
4、String内插

String内插,就是将变量插入到String字符串中,通过 $ 符号将变量插入。

fun person(name: String, age: Int) {
    println("name-->$name,age-->$age")
}

fun main(args: Array<String>) {
    person("张三", 24)
}
5、类型判断

对变量的类型进行判断,通过字符 is,判断其是否为某种类型。

fun type(x: Any) {
    when (x) {
        is Number -> println("$x is Number")
        is String -> println("$x is String")
        else -> println("don't know type")
    }
}

fun main(args: Array<String>) {
    type(3)
    type("Hello")
    type('c')
}
6、遍历map型list

map型的集合是有key-value对应值的,通过for循环对其遍历输出。

fun print(x: HashMap<String, String>) {
    for ((k, v) in x) {
        println("key -->$k,value-->$v")
    }
}

fun main(args: Array<String>) {
    val items = hashMapOf("a" to "apple", "b" to "banana", "o" to "orange")
    print(items)
}
7、区间

区间的判断,一般使用 in 对数据进行判断, 判断其是否在某个区间内。

一般来说,区间的范围,有几种表现形式:

  • x..y :x到y之间
  • x until y:x到y之间(左闭右开,不包含y)
  • x..y step z:x到y之间,只算z的整数倍
  • x downTo y:一般来说,此种情况下,都是x>y,x递减至y之间的数
fun main(args: Array<String>) {

    for (i in 1..10) {
        print("$i ")
    }

    println()
    //左闭右开区间
    for (i in 1 until 5) {
        print("$i ")
    }

    println()
    for (i in 2..10 step 2) {
        print("$i ")
    }

    println()
    for (i in 10 downTo 1) {
        print("$i ")
    }

    println()
    val i = 3
    if (i in 1..10) {
        print("$i ")
    }
}
8、访问map
(1)访问key值
  • 通过map.keys访问所有的key值
(2)访问value值
  • 通过map.values访问所有的value值
  • 通过map[key]访问特定的value值
fun main(args: Array<String>) {
    //定义为只读map
    val map = mapOf("a" to "apple", "b" to "banana", "o" to "orange")
    //访问所有的key值
    map.keys.forEach { println(it) }
    //访问所有的value值
    map.values.forEach { print(it) }
    //访问key = a 的value值
    println(map["a"])
}
9、扩展函数

在函数的基础上,对其进行扩展,增加自己想要的功能。比如扩展这样一个功能:对任意的对象转换为字符串功能。

fun Any?.changeToString(): String {
    return if (this == null) "null"
    else return toString()
}

fun main(args: Array<String>) {
    var name = 'c'
    var age = 22
    println(name.changeToString())
    println(age.changeToString())
}
10、缩写
(1)If not null 缩写

对象和调用的方法之间添加 ?,就是对其进行不为空判断。

val files = File("Test").listFiles()
println(files?.size)
(2)If not null and else缩写

在判断完之后添加 :,就是else的内容。

val files = File("Test").listFiles()
println(files?.size ?: "没有此文件")
(3)If null 执行一个语句

通过 ?:,后面为null之后所执行的语句

val values = mapOf("a" to "apple", "e" to "email")
val email = values["email"] ?: throw IllegalAccessException("Email is Missing")
println(email)
(4)If not null 执行代码

通过 ?.let{},如果为null就行let{ }里面的代码

val value = "163.com"
value?.let {
    println("已经查找到Email,地址为:" + it)
}
11、返回when表达式

通过return when(){},通过不同条件返回不同结果。

fun transform(color: String): Int {
    return when (color) {
        "RED" -> 0
        "GREEN" -> 2
        "BLUE" -> 3
        else -> throw  IllegalAccessException("no have this color")
    }
}

fun main(args: Array<String>) {
    println(transform("GREEN"))
}
12、tyr/catch表达式

try-catch抛异常执行相应操作。

fun test(age: Int): Any? {
    val result = try {
        age < 10
    } catch (e: ArithmeticException) {
        throw IllegalAccessException(e.toString())
    }
    return result
}

fun main(args: Array<String>) {
    println(test(10))
}
13、“if”表达式

通过对不同条件的判断,输出不同的结果。

fun foo(param: Int) {
    if (param == 1) {
        println("one")
    } else if (param == 2) {
        println("two")
    } else {
        println("three")
    }
}

fun main(args: Array<String>) {
    foo(2)
}
14、单表达式

如果一个函数的返回结果很简单,也可以直接写成单表达式。

同时,单表达式函数与其他惯用法一起使用,简化代码,例如和when一起使用。

//两种方式是等同的
fun theAnswer() = 42

fun theAnswer2(): Int {
    return 42
}

//单表达式函数与when一起使用
fun transform2(color: String): Int = when (color) {
    "RED" -> 0
    "GREEN" -> 1
    "BLUE" -> 2
    else -> throw IllegalAccessException("don't have this color")
}

fun main(args: Array<String>) {
    println(theAnswer())
    println(theAnswer2())
    println(transform2("RED"))
}
15、一个对象实例调用多个方法

当一个对象想要调用多个方法时,可以使用with(){},在()内填入对象,在{}内依次填入需要调用的方法。

class Turtle {
    fun penDown() {}
    fun penUp() {}
    fun turn(degree: Double) {}
    fun forward(pixels: Double) {}
}

fun main(args: Array<String>) {
    val myTurtle = Turtle()
    with(myTurtle) {
        penDown()
        for (i in 1..4) {
            forward(100.0)
            turn(90.0)
        }
        penUp()
    }
}
16、可空布尔
fun ftt(b: Boolean?) {
    if (b == true) {
        println("true")
    } else {
        print("false or null")
    }
}

fun main(args: Array<String>) {
    idiomatic_usage.ftt(true)
    ftt(null)
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值