Kotlin learning (1) - object declaration and creation

1. The difference between val and var

var means variable is the same as the definition of variable in Java, val means constant is equivalent to final in Java, here is an example:
var number = 5
number = 10
Here we define the variable number = 5 and then change the number = 10; now change the modifier to val

At this time, when the number is changed to 10, the error "val cannot be reassigned" will be reported, which translates to val cannot be reassigned, which is equivalent to the definition of final

2. Variable declaration

var number: Int?
number = 5
var number: Int? = 5
String declaration:
        
var str :String ?  = "AAA"
var s: String? = null
Object declaration:
First define a class User, the definition of the specific class will be explained in the following article, for the time being, it is only to explain the creation of the object
data class User(val name: String, val id : Int) {

   private fun getUser() : User{
       return User(name,id)
    }
}
Now let's create a User object
var user : User? = User("Name",100)
Same as the definition of the string above, has anyone thought about what's behind User? What does it mean to represent? Below we create a User object whose negative value is empty

At this time, it is found that whether the negative value of user created before is null or an empty object is re-created, the error "Null can not be a value of a non-null type User" will be reported, literally: null cannot be a negative value for non-null Type of object, it seems to mean that non-null negative values ​​cannot be null, so how to set them to be null? Yes, that's the magic "?", now we put the two objects behind the ? Fill it all in, and found that all the errors have disappeared,

Therefore, when declaring an object, it is determined whether the object can be empty or not, and the same is true for declaring constants.
val user : User ? = User("Name",100)
val  u : User ? = null
In addition, Kotlin will automatically identify the class to which it belongs, and all previous creations can be abbreviated as
var str  = "AAA"
var s = null
        
val user = User("Name",100)
val  u = null
The creation of objects of some basic data types and classes is as described above. Let's take a look at the creation of collections. Now we create a collection that stores String types.
        var list = listOf<String>("A", "B", "C", "D")
        val stringList = listOf<String>("A","B")
According to the above, the type String when the list is created can be omitted
var list = listOf("A", "B", "C", "D")
val stringList = listOf("A","B")
The declaration and creation of objects are written here. This part is very simple. Pay attention to several points of attention. You will know it after trying it yourself. I will continue to update Kotlin's methods and class creation later.



















Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325773594&siteId=291194637