当前位置:网站首页>Kotlin properties and fields
Kotlin properties and fields
2022-07-26 08:49:00 【Peace of mind】
Catalog
Declare... In the main constructor
Declare in the property initializer
Declaration of properties
Declare... In the main constructor
Use var/val Variable : type Properties can be declared
open class A(var name:String,var node:String){ override fun toString(): String { return "A(name='$name', node='$node')" //name,node The property } } fun main(args:Array<String>){ var a=A("Hellen","1") println(a) //A(name='Hellen', node='1') }
Declare in the property initializer
The specific format is :
var/val Property name [ : Attribute types ] [ = value ]
[ Access permission symbol set()=/set(){} ]
[ Access permission symbol get()=/get(){} ]
among [ ] The inside is an optional part ,var The variables are get and set Method , and val The variables are only get Method
When the attribute type can from set and get Infer when , Attribute types can be omitted , but val Only get Method , Must declare type
Generally, the specified value , You can omit the attribute type
var count=1 open class A{ var name:String // With default get, The custom set And constructor , Value ellipsis private set(value){ field=value println("set name's value") } val node:Int get() { return count++ }// Only get Default , Value cannot be omitted . Value can be specified , Omit type constructor(name:String){ this.name=name } override fun toString(): String { return "A(name='$name', node=$node)" } } fun main(args:Array<String>){ var a=A("Hellen") //set name's value var b=A("Peter") //set name's value var c=A("John") //set name's value println(a) //A(name='Hellen', node=1) println(b) //A(name='Peter', node=2) println(c) //A(name='John', node=3) }
Use of attributes
General attributes can be Use the attribute name directly visit , Yes When the names conflict, you can use this. Property name ; Outside the class, you can pass through object . Property name visit public attribute
var count=1 open class A{ var name:String set(value) { field=value println("name's set") } val node get() = count++ var kotlin_score:Int val kotlin_level:String get() { println("kotlin_level's get") return when(kotlin_score/10){ 9,10->{ "A" } 8->{ "B" } 6,7->{ "C" } else->{ "D" } } } constructor(name:String,kotlin_score:Int){ this.name=name // Name conflict , use this. Property name access this.kotlin_score=kotlin_score // Name conflict , use this. Property name access //this. Property name = Variable / value , By default, call the set function } override fun toString(): String { // No name conflicts , Access directly with the attribute name return "A(name='$name', node=$node, kotlin_score=$kotlin_score, kotlin_level='$kotlin_level')" //$ Property name , It will call the property name by default get function print( Property name ) Where the attribute name value is required, the attribute name is called by default get function } } fun main(args:Array<String>){ var a=A("Hellen",85) //name's set var b=A("Peter",100) //name's set var c=A("John",67) //name's set println(a) //kotlin_level's get //A(name='Hellen', node=1, kotlin_score=85, kotlin_level='B') println(b) //kotlin_level's get //A(name='Peter', node=2, kotlin_score=100, kotlin_level='A') println(c) //kotlin_level's get //A(name='John', node=3, kotlin_score=67, kotlin_level='C') println(c.name+" "+c.kotlin_score)// Of callable objects outside the class public attribute , object . Property name }
Behind the scenes fields
The field behind the scenes is mainly used to solve attributes set Memory overflow in function call assignment , It is mainly used to make an attribute have different values under different conditions
Generally according to Java The understanding of the ,set The function will be written as follows
var name:String set(value) { this.name=value }Write it like this IDEA It's yellow , Show unassigned setter
In this way, errors will also appear after running : Stack overflow StackOverflowError
take Kotlin Class to Java as follows , It can be seen that setName Cycle call
public class A { @NotNull private String name; @NotNull public final String getName() { return this.name; } public final void setName(@NotNull String value) { Intrinsics.checkNotNullParameter(value, "value"); this.setName(value);// Cycle call } @NotNull public String toString() { return "A(name='" + this.name + "')"; } public A(@NotNull String name) { Intrinsics.checkNotNullParameter(name, "name"); super(); this.setName(name); } }So for Solve this problem , This leads to the field behind the scenes : stay Kotlin in , If the property has at least one accessor, use the default implementation , that Kotlin Will automatically provide the field behind the scenes . Behind the scenes fields use keywords field Express , Refers to the current attribute , It can only be used for get and set Function , Therefore ,set The function is written as follows :
var name:String set(value) { field=value //field Refers to the attribute name }Be careful : Not all Kotlin Attributes have fields behind them : To meet the One of the following two situations :set and get One of them adopts the default implementation ; Self defined set and get Use in field
Behind the scenes properties
Behind the scenes properties meet : Only readable outside the class , But it is both readable and writable within the class
Implementing the behind the scenes attribute requires the declaration of two variables :
( Official requirements , But it should be possible to pass Statement var Attribute but custom public get,private set Realize the characteristics of behind the scenes properties , Just decompile Java The code is different )
private var a: Int=0 public val m_a: Int get() = a //a That is, the behind the scenes property // The compiled to : //public class A { // private int a; // // public final int getM_a() { // return this.a; // } //}var a:Int=0 private set(value){ field=value }//get Default public // The compiled to //public class A { // private int a; // // public final int getA() { // return this.a; // } // // private final void setA(int value) { // this.a = value; // } //} // More official , Decompile more set function
边栏推荐
- Excel delete blank lines
- P3743 Kotori's equipment
- [suggestions collection] summary of MySQL 30000 word essence - locking mechanism and performance tuning (IV) [suggestions collection]
- sklearn 机器学习基础(线性回归、欠拟合、过拟合、岭回归、模型加载保存)
- The effective condition of MySQL joint index and the invalid condition of index
- 2022年收益率最高的理财产品是哪个?
- Excel find duplicate lines
- 基于C语言实现的人机交互软件
- keepalived双机热备
- [recommended collection] MySQL 30000 word essence summary index (II) [easy to understand]
猜你喜欢

Poor English, Oracle OCP or MySQL OCP exam can also get a high score of 80 points
![[abstract base class inheritance, DOM, event - learning summary]](/img/0e/4c4ed97814d49d72a5994ce2a53c88.png)
[abstract base class inheritance, DOM, event - learning summary]

In the first year of L2, the upgrade of arbitrum nitro brought a more compatible and efficient development experience

C#入门系列(三十一) -- 运算符重载

Cadence(十)走线技巧与注意事项

合工大苍穹战队视觉组培训Day5——机器学习,图像识别项目

Mycat2 sub database and sub table

pl/sql之集合

Pxe原理和概念

Xshell batch send command to multiple sessions
随机推荐
Study notes of automatic control principle -- dynamic model of feedback control system
Oracle 19C OCP 1z0-082 certification examination question bank (13-18)
Xshell batch send command to multiple sessions
【数据库 】GBase 8a MPP Cluster V95 安装和卸载
Flitter imitates wechat long press pop-up copy recall paste collection and other custom customization
Oracle 19C OCP 1z0-083 question bank (1-6)
Pxe原理和概念
6、 Pinda general permission system__ pd-tools-log
Ansible important components (playbook)
Solve the problem of C # calling form controls across threads
pl/sql之动态sql与异常
Problems caused by slivereappbar
Oracle 19C OCP 1z0-082 certification examination question bank 1
Leetcode and query question summary
Huffman transformation software based on C language
P1825 [USACO11OPEN]Corn Maze S
After MySQL 8 OCP (1z0-908), hand in your homework
[C language] programmer's basic skill method - "creation and destruction of function stack frames"
Vision Group Training Day5 - machine learning, image recognition project
Fluent custom popupmenubutton


