Kotlin .. Java Concepts Clarification(1): Property and Field
来源:互联网 发布:it项目经理 编辑:程序博客网 时间:2024/05/29 11:39
Kotlin .. Java concepts clarification(1): Property and Field
在Kotlin中引入了property的概念,但property并非等同于Java中的fields:
- property隐式的包含了fields,但比fields更高级,例如下面的两段代码是等同的:
// Kotlinvar name: String = "Kotlin"
// Javapublic String name = "Java"public String getName(){ return name;}public void setName(String name){ this.name = name;}
- Kotlin中的property不仅提供了数据存储的字段,也隐式的声明了accessor(包括setter和getter)。accessor 也可由用户自定义,例如如果我们希望得到标题格式的String数据,可以在get之前将其转换成大写格式:
// Kotlinvar name: String = "kotlinget() = field.capitalize()print(name)// prints: Kotlin
- 或者忽略null赋值,只接受非空赋值
// Kotlinvar name: String = "kotlin" set(String value){ if(value != null) field = value }name = "kotlin"print(name)// prints: kotlinname = ""print(name)// prints: kotlin
Property的行为是由它的accessor决定的,并非必要涉及fields。但在自定义accessor的时候,可以通过fields(backing fields)获得该propert的数据。
- 我们可以在interface里面定义property,就像这样:
// Kotlininterface Example{ val name: String}
这意味着,在implements该interface的classes里面,必须要定义该val的getter。
Kotlin里面的property给了用户更多选择,是比Java中的fields更高级的概念。
参考:
https://blog.kotlin-academy.com/kotlin-programmer-dictionary-field-vs-property-30ab7ef70531
阅读全文
0 0
- Kotlin .. Java Concepts Clarification(1): Property and Field
- Clarification of General Concepts- User Space , Kernel Space and PGD and CR3
- Kotlin基础语法-属性(Property)与域(Field)
- Java Concepts for Java 5 and 6
- OOPs and Its Concepts in Java
- Next Generation Java Testing: TestNG and Advanced Concepts
- Field, Property, Attribute
- RAC Architecture and Concepts
- static field and method in java
- Database System Concepts (1) -- Data Storage and Querying
- CILP Programming Concepts – Assignment 1 and 2
- Java Field[] Field理解
- Ip Multicasting: Concepts and Applications
- PnR basic - Terms and Concepts
- Some JDeveloper Concepts and Tips
- [Network]Introduction and Basic concepts
- Basic jpa and hibernate concepts
- Spring ContextLoaderListener And DispatcherServlet Concepts
- Specified key was too long; max key length is 721bytes
- Oracle可不可以自动添加数据文件
- java为移动端写接口
- 66. Plus One
- 【MongoDb学习之路】 MongoDb 基本操作命令
- Kotlin .. Java Concepts Clarification(1): Property and Field
- 数据结构与算法(一)数据解析
- Linux目录操作
- centos7安装chrome浏览器
- anaconda
- c3p0,dbcp与druid 三大连接池的区别
- Android开发之电话服务、SMS短信监听
- Linux:多线程编程
- NYOJ 47 过河问题