Koltin简明学习,解构声明
来源:互联网 发布:喜马拉雅网络加载失败 编辑:程序博客网 时间:2024/06/08 05:22
解构声明(Destructuring Declarations):个人理解,是一种通过方便的方法得到一个对象的成员变量
普通应用
我们在一个文件中定义一个Person类
data class Person(val name: String, val age: Int)
我们可以通过简单的语法获得这个类的name和age属性
val (name, age) = Person("tom", 11)println(name)println(age)
属性结果是:
I/System.out: tomI/System.out: 11
上面的Person是数据类(data class)当我们定义一个普通的类,看看
class Dog(val name: String, val age: Int)
我们发现不能简单的通过下面的方法获取name和age的值
val (nameDog, ageDog) = Dog("James", 5)
为什么数据类可以,普通类就不可以呢?
因为数据类帮我们实现了解构声明需要的componentN方法这个N可以是1或者2等.
我们重新定义Dog类:
class Dog(val name: String, val age: Int) { operator fun component1() = name operator fun component2() = age}
val (nameDog, ageDog) = Dog("James", 5)println(nameDog)println(ageDog)
上面的代码打印输出:
I/System.out: JamesI/System.out: 5
方法返回两个值
不解释,看代码
data class Result(val result: Int, val status: Status)fun function(...): Result { // computations return Result(result, status)}// Now, to use this function:val (result, status) = function(...)
解构声明和Map
通过解构声明变量Map,打印key和value
val map = mapOf<Int, String>(1 to "one", 2 to "two", 3 to "three")for ((a, b) in map) { print("$a-") println(b)}
输出:
I/System.out: 1-oneI/System.out: 2-twoI/System.out: 3-three
转换一个Map的value值
val map = mapOf<Int, String>(1 to "one", 2 to "two", 3 to "three")val map2 = map.mapValues { (key, value) -> "android_$value" }for ((a, b) in map2) { print("$a-") println(b)}
输出:
I/System.out: 1-android_oneI/System.out: 2-android_twoI/System.out: 3-android_three
参考文献
https://kotlinlang.org/docs/reference/multi-declarations.html
Kotlin简明学习—文章列表
阅读全文
0 0
- Koltin简明学习,解构声明
- Koltin简明学习,also,takeIf,takeUnless
- Koltin简明学习,扩展方法和扩展属性
- Koltin简明学习,操作符重载(Operator overloading)
- Koltin数据类之解构申明
- Kotlin学习笔记(十)解构声明
- Kotlin学习(十五): 解构声明(Destructuring Declarations)
- koltin学习教程 androidstudio 使用koltin 语言编程
- Kotlin-解构声明
- Kotlin-解构声明
- Kotlin解构声明
- 学习kotlin第13天_具体化的类型参数、内联属性、解构声明、集合
- ES6学习-解构
- ES6学习---解构
- ES6学习笔记:解构
- ES6--变量的声明及解构赋值
- android kotlin其它(一)解构声明
- Kotlin-25.解构声明(Destructuring Declaration)
- 无法修正错误,因为您要求某些软件包保持现状,就是它们破坏了软件包间的依赖关系
- DWR框架实现服务器推送时的一个小问题
- 干货 | 36个大数据文档PDF开放下载
- 21、shell编程简介
- 高德地图,百度地图坐标系GPS的转化
- Koltin简明学习,解构声明
- OpenCV代码提取:remap函数的实现
- EditText
- ADG swicthover操作(主备切换)
- k8s-configmap 创建
- JAVA源码解析(11)-java.beans.XMLEncoder、java.beans.XMLDecoder(一)
- Mybatis Generator 使用(Maven插件)
- centos7在线lvm扩容
- 系列:iOS开发-从扩展UIButton到自定义控件