Introduction to kotlin properties and functions (compared with Java)

Little fish people love programming 2022-05-14 15:00:23 阅读数:936

introductionkotlinpropertiesfunctionscompared

Preface

Kotlin It has been out for several years , Especially as Android Officially designated development language , Many items have been replaced with Kotlin To write , Popular third-party libraries are also beginning to support Kotlin. In the use of Kotlin In the process of , You will gradually understand its advantages and learn to make the best use of it .
Through this article , You will learn :

1、 Why do you need properties and functions
2、Kotlin Properties,
3、Kotlin Function details

1、 Why do you need properties and functions

image.png

Simply speaking :

Attributes are input parameters , A function is the body of a procedure that deals with variables

therefore , In the field of high-level language , Properties and functions are the foundation .

2、Kotlin Properties,

Property declaration

Kotlin The keyword of attribute declaration is var And val,var yes variable Abbreviation ,val yes value Abbreviation .var The value pointed to is variable , You can assign other values to it later , and val Is a constant , It cannot be changed after initialization .
There are two kinds of attributes :

Constant & Variable

//kotlin
// Variable
var num: Int = 3
// Constant
val age: Int = 4
//java
// Variable
int num = 3;
// Constant
final int age = 4;
 Copy code 

And Java The difference between attribute declarations is ,Kotlin Need to use var/val Declarative attribute , And the attribute type is written in ":" Back , You might have said : Well said Kotlin What about simplicity , I also wrote a few more words ?
actually Kotlin Type inference can be made , For example, the attributes declared above can be rewritten as follows :

//kotlin
// Variable
var num = 3
// Constant
val age = 4
 Copy code 

omitted ":" And type , Compiler auto inference num And age The type of Int.
Of course , if :

//kotlin
// Variable
var num = 3.4
 Copy code 

So at this time num by Double type .

Attribute types

image.png

It can be seen that ,Kotlin There are no so-called basic data types in the , And inside it " Basic data type reference " And Java The basic data type corresponds to , similar Java The wrapper class .
Let's look at data type conversion :

var numInt : Int = 4
var numLong : Long = 5
//kotlin transformation
fun test() {
// Not allowed to
numInt = numLong
numLong = numInt
// allow
// From large range to small range, overflow may occur
numInt = numLong.toInt()
numLong = numInt.toLong()
}
//Java transformation
void test() {
int a = 5;
// Small to big allow
long b = a;
// Big to small allow
a = (int) b;
}
 Copy code 

so :Kotlin Big to small 、 The transformation from small to large depends on toXX() Function .

Attribute access

Global properties

The above declared properties / Function defined in :VarTest.kt in , Now separate from another Kotlin Document and Java Access them in the file .

Kotlin I'm going to visit

#Start.kt
fun main(args:Array<String>) {
// assignment
num = 3.4
// Value
var numLong2 = num
// Call function
test()
}
 Copy code 

Java I'm going to visit

 void test2() {
// Calling method
VarTestKt.test2();
// Get variable
VarTestKt.getNum();
// Set a variable
VarTestKt.setNum(33);
}
 Copy code 

stay VarTest.kt There is no declared class in the , Therefore, the attributes declared directly in the file / function It has global characteristics , In the final compiled bytecode :

Properties are static properties , Functions are static methods .VarTest.kt Will be compiled as VarTestKt Java class , So in Java They can be accessed through static methods in the code .
And in the Kotlin Access them directly in the .

VarTest.kt The compiled bytecode is decompiled as follows :

#TestJava.java
public final class VarTestKt {
private static double num = 3.4D;
public static final double getNum() {
return num;
}
public static final void setNum(double var0) {
num = var0;
}
public static final void test2() {
...
}
}
 Copy code 

If you want to Java In the document directly through .xx How to access properties , Need to be in VarTest.kt Add to file @JvmField modification

#VarTest.kt
@JvmField
var num = 3.4
 Copy code 

stay Java Call in as follows :

#TestJava.java
void test2() {
// Calling method
VarTestKt.test2();
// // Get variable
// VarTestKt.getNum();
// // Set a variable
// VarTestKt.setNum(33);
// Direct access to properties
VarTestKt.num = 2.4;
double num = VarTestKt.num;
}
 Copy code 

It should be noted that : about Java Come on , here num The access rights of the property are public, And its default get/set There's no way , stay Java Only through .num Visit it , Not through getNum/setNum visit .

Class member properties

 Declare attributes first
#VarTestClass.kt
class VarTestClass {
var num:Int = 3;
}
 Copy code 

Kotlin I'm going to visit

fun main1() {
// The new object
var varTestClass = VarTestClass()
// assignment
varTestClass.num = 3
// Get value
var num = varTestClass.num
}
 Copy code 

Java I'm going to visit

#TestJava.java
void test3() {
// The new object
VarTestClass varTestClass = new VarTestClass();
varTestClass.getNum();
varTestClass.setNum(3);
}
 Copy code 

Compared with global attributes , Class member properties depend on the class , So to access them, you need to create a new object , Access through objects . Other access methods are the same .

Attribute permissions and initialization

Access control rights

image.png

Koltin The default is public, Therefore, in most cases, you can directly access properties .
If you use private Modify properties , Then... Will not be generated get/set Method .

initialization

Initialization time
stay Java in Attribute initialization can be completed by assigning a value to the attribute while declaring the attribute , And for Kotlin For example, you can choose not to initialize immediately . Look at constants first val initialization :

// Normal initialization
val myNum = 4
// Delay initialization Constant
val myNum2:Int by lazy { 3 }
 Copy code 

It seems that delaying initialization is useless ? Let's look at the delayed initialization of reference types

class MyBean {
var age = 3
}
// Normal initialization
val myBean = MyBean()
// Delay initialization
val myBean1:MyBean by lazy {
MyBean()
}
 Copy code 

In this way, the effect is more obvious , When used myBean1 Only when MyBean object , Save memory .
notes :by and lazy It's all functions
When we use by lazy An error will be reported when delaying the initialization of variables .

var myBean1:MyBean by lazy {
MyBean()
}
 Copy code 

Delayed initialization of variables requires another keyword :lateinit

// Variables are initialized normally
var name:String = "fish"
// Variable delay initialization
lateinit var name1:String
fun useName() {
name1 = "fish1"
}
 Copy code 

It should be noted that , The following methods will not be allowed :

// error , Cannot decorate basic types
lateinit var num3:Int
// error , Cannot decorate an empty type
lateinit var name2?:String
 Copy code 

In conclusion , Property can choose to delay initialization :

var Use lateinit, This keyword cannot modify a base type (Int etc. )
val Use by lazy

get/set The way
stay Java For attributes, we usually use get/set Operate it ,Kotlin Although it is automatically generated get/set Method , But sometimes we need to be right get/set Do extra work , So you can rewrite them .

var myName: String = ""
get() {
// Get value
var age = 2
if (age > 18)
return field
return ""
}
set(value) {
// Set the value
if (value == "fish")
field = value
}
 Copy code 

field Called back-end variables , Is the actual value of the variable , Here is myName The real value of .

Be careful :get/set Can't be used in myName, Because of the visit myName It's essentially through get/set Method , Will cause infinite recursive access , So you need to use field.

3、Kotlin Function details

Different names

stay Java in :

 void test4() {
}
 Copy code 

Called method
And in the Kotlin in :

fun test4() {
}
 Copy code 

Called a function

Formal parameter and return value

fun test4(name : String):String {
return "hello"
}
 Copy code 

Declaring a function requires a custom keyword :fun
Similar to the definition of attributes ,: After, it indicates the return type .
name:String Indicates a formal parameter .

Looks like Java Little difference , Then let's look at the details .
Kotlin If the function has no return value , Then use Unit Express :

fun test5(name: String):Unit {
}
 Copy code 

similar Java Inside Void.
Generally speaking , Here Unit It can be omitted , Changed to the following :

fun test5(name: String) {
}
 Copy code 

Named parameters and default parameters

Let's start with named parameters :

// Function declaration
fun testV2(name: String, age: Int, score: Double) {
}
 Copy code 

Call this function :

fun main2() {
testV2("fish", 5, 4.5)
}
 Copy code 

When we look at it testV2 Invocation time , It may not be possible to see at a glance how arguments and formal parameters correspond to , At this point, you need to name the parameters ( Named parameters ):

fun main2() {
testV2("fish", 5, 4.5)
testV2(score = 4.5, name = "fish", age = 5)
}
 Copy code 

" name " As the name suggests, you can specify the name of the formal parameter and the value of the argument , When using named parameters , The order of parameters can be changed .
It should be noted that : Other parameters followed by named parameters also need to be written in the form of named parameters .
For example, the following are compilation errors :

 testV2(score = 4.5, name = "fish", 5)
 Copy code 

Again, the default parameters :

fun testV4(name: String = "fish", age: Int, score: Double){
}
 Copy code 

name The default value is "fish", call testV4() as follows :

fun main3() {
testV4(score = 4.5, age = 5)
}
 Copy code 

Now if name The value has not changed , You don't have to pass , Use the default value .
It should be noted that : When default parameters are not passed , Other parameters need to be passed in the way of named parameters .
Of course , If the default parameter is the last value , Then other parameters can pass values directly without using the named parameter form .

fun testV4(name: String = "fish", age: Int, score: Double = 4.5){
}
fun main3() {
testV4("fish", 4)
}
 Copy code 

Java There are no named parameters and default parameters in .

Variable parameters

Java Variable parameters in :

 void test(String... names) {
for (String name : names) {
Log.d("fish", name);
}
}
 Copy code 

Koltin The variable parameter in is :

fun testV5(vararg name:String) {
name.forEach {
println(it.length)
}
}
 Copy code 

adopt vararg Statement .
stay Kotlin Call in as follows :

fun main4() {
testV5("fish", "fish2", "fish3")
}
 Copy code 

The function classification

Depending on the scope of the function , It can be divided into the following :

image.png

Top level function

It's defined in Koltin Functions in files , Class independent .
stay Start.kt The definition in the document is as follows :

fun main4() {
testV5("fish", "fish2", "fish3")
}
class MyStart {
}
 Copy code 

here main4 And MyStart It doesn't matter , It exists in Start.kt Inside , Other files access this method is the same as accessing the global ( top floor ) Properties are similar to .

Class member function

class MyStart {
fun start() {
}
}
 Copy code 

start() For member functions , External access is similar to accessing class member properties .

Class constructor

There are many knowledge points involved , The next analysis .

Nested function

seeing the name of a thing one thinks of its function : Function in function .

class MyStart {
fun start() {
fun end() {
}
// call
end()
}
}
 Copy code 

here end For nested functions , Main uses :

1、 Recursive function .
2、 Function internal unified logic extraction , I don't want to be exposed to the outside .

And Java comparison ,Kotlin Property changes are not particularly large , What has really changed is Kotlin Function of .
The above is just a brief introduction to some basic knowledge of functions , It also has some more advanced features :
spread function 、 Function parameter / Return value For the function 、 Function expression 、 The function of generic 、Lambda etc. , Understanding this knowledge is the premise of understanding the collaborative process .
We will complete these knowledge points in the next article .

This article is based on Kotlin 1.5.3, In this paper, Demo Please click on

If you like , Please thumb up 、 Focus on , Your encouragement is my driving force

Ongoing update , Step by step with me 、 Learn more Android/Kotlin

1、Android Various Context The past and this life
2、Android DecorView Will know
3、Window/WindowManager Something you don't know
4、View Measure/Layout/Draw I see
5、Android Event distribution full service
6、Android invalidate/postInvalidate/requestLayout Thoroughly clarify
7、Android Window How to determine the size /onMeasure() Multiple execution reasons
8、Android Event driven Handler-Message-Looper analysis
9、Android One move with the keyboard
10、Android The coordinates are completely clear
11、Android Activity/Window/View Of background
12、Android Activity Create to View The display of
13、Android IPC series
14、Android Storage series
15、Java Concurrent series is no longer in doubt
16、Java Thread pool series
17、Android Jetpack Front Foundation Series
18、Android Jetpack Easy to learn and easy to understand series

版权声明:本文为[Little fish people love programming]所创,转载请带上原文链接,感谢。 https://javamana.com/2022/134/202205141446337533.html