This article is only for recording learning, so if there are some mistakes or wrong understanding, please correct. This article is the CSDN original article transfer modified version of the original article
tool
- For Android development, you can use Android Studio. When creating a new project, please remember to check supper Kotlin, which is similar to the operation of JNI development. If you are using android Studio 3.0 or later, you will need to search for kotlin in File /setting/plugins /.
- If you are learning like me, you can use idea to create a new Kotlin project and contact with it.
1. HelloWorld and package declarations
Defining packages in Kotlin is a little different from Java. In Kotlin, there is no need to match the directory and package structure.
The source code for Kotlin can be anywhere on disk.
Package com.ymc. helloKotlin Fun Main (args: Array<String>) {println("Hello world") println(Max (2,3))} fun Max (a:Int,b:Int):Int{return if(a>b) a else b; }Copy the code
2. Fun represents a function, followed by the function name, argument list, and return value type 3. The parameter implementation writes the parameter name and colon separated, and then writes the parameter type (as opposed to Java) 4. The return value of a function is followed (as opposed to Java). It is also possible to write no return type (if: Only the return type of the expression body function can be omitted. If the function is a code block function, you must specify the return type of the function. You can omit the semicolon at the end of the line (similar to js). 7. See that if in the Max function is similar to the ternary expression kotlin, where if is an expression with a result value 8. If the return value is similar to void in Java, you can write it as :Unit, or you can omit it
In Kotlin, most control structures except for partial loops (for do and do/while) are expressions that have return values. Assignment statements in Java, on the other hand, are expressions, whereas in Kotlin they are statements. In the same way that Java defines package names, define the package name at the beginning of the source file: however, the package name and folder path can be different: the source file can be placed anywhere in the project, and it is not recommended to do so.
2. The variable
Given that kotlin variable declarations can omit types, kotlin variable declarations differ from Java in that they are declared in the order of the keyword variable name type (optional), and explicitly indicate the variable type if the variable is not initialized.
Constants and variables can have no initialized value, but must be initialized before reference. The compiler supports automatic type determination, that is, the declaration can not specify the type, the compiler to determine. The type of the variable must be supplied if it is not initialized at declaration time
val name = "ymc"
val age = 23
val age1 : Int = 23
val age2 :Int
age2 = 24
Copy the code
Var: an immutable reference, which cannot be assigned to a variable after val is declared (Java final). Var: a mutable reference, which can be assigned to any type of variable
1, variable definition: var keyword
Var < variable name > : < variable type > = < initial value >
Var sum = 3 sum = 8 var sum = 3 sum = 8Copy the code
2, immutable variable definition: val keyword, can not be assigned twice, similar to Java final type
Val < constant name > : < constant type > = < initial value >
Val sum: Int // Sum = 5Copy the code
Attributes with known values can be marked as compile-time constants using the const modifier. The following conditions (similar to the constant value in constanUtil in Java) are met
- A member of a top-level or object
- Class with a String or native type value
- There’s no custom getter
Const val SUBSYSTEM_KEY: String = "key" @deprecated (SUBSYSTEM_KEY) fun () {... }Copy the code
3. String template
Println ("Hello world ${age[0]}") println("Hello world ${age[0]}" Var s1 = "a is $a" val s2 = "${s1.replace("is", "was")}, but now is $a" var s1 = "a is $a" val s2 = "${s1.replace("is", "was")}, but now is $a"Copy the code
4. Classes and attributes
4.1 class
Let’s compare the way classes are written in Java and kotlin
java
public class DemoBean { private final String name; public DemoBean(String name) { this.name = name; } public String getName() { return name; }}Copy the code
kotlin
class DemoBean(val name: String)
Copy the code
If you are a lagging kotlin beginner like me, we can still develop mainly in Java language in our daily life. If we need to see the effect of Kotlin, we can copy Java code to kt file, idea will automatically prompt us to convert.
4.2 attributes
Class, where we encapsulate the data and the code that handles it into a single entity.
Class Person{var name :String = "ymc" // var isMarried: Boolean = false // read-only}Copy the code
IsMarried generates a field, a getter, and name generates a getter and a setter. When you declare a property in Kotlin, you declare an accessor. The default accessor is the getter that returns the value and the setter that updates the value. Kotlin exposes a getName method, but we can also customize accessors.
fun main(args: Array<String>) { var person = Person() println(person.name +";" + person.isMarried ) }Copy the code
You can see that we call it directly without the need for get, which feels a lot like JS…
4.3 Customizing Accessors
class Person{ var name :String = "ymc" var sex : Int = 0; Val isBoy :Boolean get() {return if(sex==1) true else false}} val isBoy :Boolean get() {return if(sex==1) true else false}}Copy the code
We add the sex and isboy properties to Person, overriding the getter, so we can customize the accessor.
If we set the property to val but modify the property with a custom getter does the property change?
fun main(args: Array<String>) {
val name = "Hello Kotlin"
name = "Hello Java"
}
Copy the code
If you simply modify it, you will report an error
Error:(8, 5) Kotlin: Val cannot be reassigned
Copy the code
Next, let’s look through custom accessors
class RandomNum {
val num: Int
get() = Random().nextInt()
}
fun main(args: Array<String>) {
println("the num is ${RandomNum().num}")
}
Copy the code
the num is -1251923160 the num is -1527833641
Conclusion: The above example shows that hypothesis 1 is true. The val modifier in Kotlin cannot be said to be immutable, but only readable.
4.4 Secondary Fields
Fields are not allowed in Kotlin, so we can use alternate fields, such as the next code, to act as local variables.
Var counter = 0 get() = field set(value) {if (value >= 0) field = value} // Val isEmpty: Boolean get() = this.size == 0Copy the code
Note: The field identifier is only allowed within the accessor function of a property.
4.5 Delayed initialization of properties and variables
Properties declared as non-empty must be initialized in the constructor. To handle this, you can tag the property with the lateinit modifier:
public class MyTest { lateinit var subject: TestSubject @setup fun SetUp () {subject = TestSubject()} @test fun Test () {subject.method()}}Copy the code
That way, we don’t need to initialize the function at constructor time, but call setup wherever we need to.
5. Null check mechanism
Kotlin’s null security design for the declaration can be null parameters, in the use of empty judgment processing, there are two ways to deal with the field after!! Throw an empty exception like Java, another type of field followed by? Do not do anything to return null or cooperate? : Short judgment processing
// Add? Var age: String? = "23" // add "!!" Val ages = age!! .toint () // Add "? Null val ages1 = age? .toint () // use "? Val ages2 = age? .toInt() ? 1: -Copy the code
In Kotlin if the value or the return value can be null then you can add?
fun getStringLength(obj: Any): Int? {if (obj is String) {// 'obj' is automatically converted to 'String' type in this branch return obj.length} // 'obj' is still 'Any' type return null} fun getStringLength(obj: Any): Int? {// 'obj' is automatically converted to String in this branch if (obj! is String) return null return obj.length }Copy the code
This method returns the length of the string, which can be null or int. In this case, we see the new word is. The is expression checks to see if the type of the expression or value is the type after is. If not, the original data type is retained.
In the previous code we can see the difference between kotlin’s and Java’s conversions. Java uses instanceOf to determine the type, and if we want to convert it to the type we are comparing, we need to explicitly convert it to the type we are comparing. Kotlin uses is to check the data. If the type is correct, the transition is intelligent, which the compiler does for us automatically. (val n = A as Num) (val n = A as Num)
Kotlin’s Study Notes (2)