Kotlin学习(3):习惯用法
生活随笔
收集整理的这篇文章主要介绍了
Kotlin学习(3):习惯用法
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
- 开发环境:IntelliJ IEDA
- 个人博客:http://blog.csdn.net/IInmy
- 项目源码:https://github.com/Rushro2m/KotlinForOfficial
- 官方文档中文版:https://www.kotlincn.net/docs/reference/idioms.html
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之间的数
8、访问map
(1)访问key值
- 通过map.keys访问所有的key值
(2)访问value值
- 通过map.values访问所有的value值
- 通过map[key]访问特定的value值
9、扩展函数
在函数的基础上,对其进行扩展,增加自己想要的功能。比如扩展这样一个功能:对任意的对象转换为字符串功能。
fun Any?.changeToString(): String {return if (this == null) "null"else return toString() }fun main(args: Array<String>) {var name = 'c'var age = 22println(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" -> 3else -> 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() = 42fun theAnswer2(): Int {return 42 }//单表达式函数与when一起使用 fun transform2(color: String): Int = when (color) {"RED" -> 0"GREEN" -> 1"BLUE" -> 2else -> 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) }总结
以上是生活随笔为你收集整理的Kotlin学习(3):习惯用法的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: xsl:apply-templates和
- 下一篇: oracle maven依赖