当前位置:网站首页>Kotlin Foundation

Kotlin Foundation

2022-06-25 12:15:00 User 9854323

List of articles

One . Kotlin Basic knowledge of

1. HelloWorld:

fun main(args: Array<String>){
    System.out.println("hello world")
}

2、 Common data types

3、 Type inference

4、 Value range

var aByte:Byte = Byte.MAX_VALUE
var bByte:Byte = Byte.MIN_VALUE

5、 function

fun checkAge(age: Int): Boolean{
    if(age > 18) return true else return false
}

6、 Character template

fun diaryGeneraer(placeName: String){
    var temple = """ It's sunny today , cloudless , Let's go to the ${placeName} play ,"""
    println(temple)
}

7、 String comparison

And Java It's different ,kotlin in “==” and equals() equally ,equals( , true) Ignore case

8、 Method parameters and null

fun test(){
    heat(null)     // Compile 
    heat1(null)    // Compile but 
}

// Parameters str It can be transmitted null
fun heat(str: String?): String{
     return str + " heat "
}

// Parameters str  You can't pass null
fun heat1(str: String): String{
    return str + " heat "
}

9、when Conditional statements

fun gradeStudent(score: Int){
    when(score){
        10 -> println(" Got full marks ")
        8 -> println(" just so so ")
        6 -> println(" Just passed ")
        3 -> println(" No way. ")
        else -> println("other")
    }
}

when Advanced conditional statements

fun diaryGenerator(placeName: String){
    var diary = """ It's sunny today , We went to ${placeName} play ,
        | The first thing that comes into view when you enter the gate is ${placeName}
        |${strNum(placeName.length)} A large gold plated character """.trimMargin()

    print(diary)
}


fun strNum(score: Int): String{
   var result = when(score){
        1 -> " One "
        2 -> " Two "
        3 -> " 3、 ... and "
        4 -> " Four "
        else -> " The place name is too long "
    }
    return result
}

9、 loop and Section

fun main(): Unit{
    var nums = 1 .. 100   // Closed interval [1, 100]
    var result = 0;
    for(num in nums){     // loop :in You can take out the numbers in the array 
        result = result + num
    }

    print(" The result is " + result)
    print(" The result is ${result}")
}

 Open range :
var nums = 1 until 100   // Closed interval [1, 100)

step:
var nums = 1 .. 100
for(num in nums step 2){
    print("${num} ,")
}

 reverse :
var nums = 1 .. 100
var nums1 = nums.reversed();
for(num in nums1 step 2){
    print("${num} ,")
}

10、list And map

  1. list No index
var lists = listOf<String>(" rice ", " egg ", " millet ", " Coix seed ")
for(str in lists){
    print(str)
}
  1. list belt index
var lists = listOf<String>(" rice ", " egg ", " millet ", " Coix seed ")
for((i, str) in lists.withIndex()){
    print("" + i + " " + str)
    print("$i  $str")
}
  1. Map
var map = HashMap<String, String>()
map["good"] = " good "
map["yes"] = " yes "
map["no"] = " No "

for(str in map){
    println(str)
}

println(map.get("good"))
println(map["good"])

11、 Functional expression

//1、
fun add(x: Int, y: Int): Int{
    return x + y
}

//2、 When the function body has only one sentence of code :,
fun add(x: Int, y:Int):Int = x + y

//3、 It can be written like this 
var sum = {x:Int, y:Int -> x+y}
var i = sum(3, 5)    // call 

//4、
var sum1:(Int, Int) -> Int = {x,y -> x + y}

12、 Default and named parameters

fun main(): Unit{
    sum()
    sum(1, 3)
    sum(x = 3)
    sum(y = 9)   // Named parameters 
}

// Default parameters 
fun sum(x:Int = 2, y:Int = 5): Int{
    return x + y
}

13、Stirng And Int Interturn

fun main(): Unit{
    var str = "123"
    var int = 123;
    var strInt = "123abc"

    int  = str.toInt();
    str = int.toString();
    int = strInt.toInt();   // The compiler will report an error java.lang.NumberFormatException: For input string: "123abc"
}

14、 exception handling

while (true) {
    println(" Please enter a number ")
    var str = readLine()
    try {
        var int = str!!.toInt()
    }catch (e: Exception){
        println(" eldest brother , To enter numbers ")
    }
}

15、 Tail recursive optimization

Two 、 object-oriented

1、 Inherit

open class Fathor{           // To be inherited requires open
    var chactor: String = " introversion "
    open fun action(){      // Need to be copied open
        println(" Like to think ")
    }
}

class Son: Fathor(){  
    override fun action() {      // Replication requires override
        println(" My son is very good ")
    }
}

2、 Interface

interface Iman {
    fun say()
}

abstract class Human(var name:String){
    abstract fun eat()
}

class Man(name: String) : Human(name), Iman {

    override fun eat() {
        println(" Take a big bite ")
    }

    override fun say() {
    }
}

3、 Agency and entrustment by

interface IWash {
    abstract fun wash();
}

class BigHeadChild : IWash {
    override fun wash() {
    }
}

class SmallHeadFather : IWash by BigHeadChild(){
   override fun wash() {
        println(" I'm big daddy , My son helped me wash the dishes ")
        BigHeadChild().wash()
   }
}

4、 Single case object

object BigHeadChild : IWash {
    override fun wash() {
    }
}

 When called () Get rid of 
class SmallHeadFather : IWash by BigHeadChild{

    override fun wash() {
        println(" I'm big daddy , My son helped me wash the dishes ")
        BigHeadChild.wash()
    }
}

5、 enumeration and Seals

enumeration : Focus on data

fun main(): Unit{
    println(Week. Monday )
    println(Week. Monday .ordinal)
}

enum class Week{
     Monday ,  Tuesday ,  Wednesday ,  Thursday ,  Friday ,  Saturday ,  Sunday ,
}

Seals : Focus on type

fun main(): Unit{
    var s1:Son = Son. Little donkey ()
    var s2:Son = Son. Mule ()
}

sealed class Son{
    fun sayHello(){
        println(" Hello everyone ")
    }
    class  Little donkey () : Son()
    class  Mule (): Son()
}

3、 ... and 、 Higher order function ( Parameters / The return value is the function )(forEach,map,flatmap,fold,reduce,filter,takeWhite,let/run,also/apply,with,use)

//maxBy
printGirl(grilList.maxBy { it.height })    //Java  You need to iterate through 

//minby
printGirl(grilList.minBy { it.height })

//filter
println(grilList.filter {
    (it.height > 123) and (it.height < 1234)
})

//map
var result = grilList.map { "${it.name} : ${it.height}" }
println(result)

//any   Is there a 
println(grilList.any{ it.height == 1253})

//count
println(grilList.count{ it.height <= 1253})

//find  Find the first qualified 
println(grilList.find{ it.height == 1253})

//groupBy    Group according to different conditions 
println(grilList.groupBy{ it.address})
println(grilList.groupBy{ it.address}.get(" Beijing "))
println(grilList.groupBy{ it.address}.get(" Beijing ")?.forEach { printGirl(it) })

//let
grilList.get(0)?.let { printGirl(it) }

1、let The applicable scenario of the function

Reference resources :https://blog.csdn.net/u013064109/article/details/78786646 Scene one : The most common scenario is to use let Function processing needs to be directed at a null All objects are subject to space judgment . Scene two : Then it is necessary to specify that a variable can be used within a specific scope

 Don't use let, Not elegant enough 

mVideoPlayer?.setVideoView(activity.course_video_view)
mVideoPlayer?.setControllerView(activity.course_video_controller_view)
mVideoPlayer?.setCurtainView(activity.course_video_curtain_view
)

 Use let
mVideoPlayer?.let {
           it.setVideoView(activity.course_video_view)
           it.setControllerView(activity.course_video_controller_view)
           it.setCurtainView(activity.course_video_curtain_view)
}

2、with Applicable scenarios of function

When calling multiple methods of the same class , Class name repetition can be omitted , Call the method of the class directly , Often used for Android in RecyclerView in onBinderViewHolder in , data model Properties of map to UI On :

 Not used with front :
@Override
public void onBindViewHolder(ViewHolder holder, int position) {

   ArticleSnippet item = getItem(position);
              holder.tvNewsTitle.setText(StringUtils.trimToEmpty(item.titleEn));
           holder.tvNewsSummary.setText(StringUtils.trimToEmpty(item.summary));
                String gradeInfo = " difficulty :" + item.gradeInfo;
                String wordCount = " Number of words :" + item.length;
                String reviewNum = " Journal entry :" + item.numReviews;
                String extraInfo = gradeInfo + " | " + wordCount + " | " + reviewNum;
                holder.tvExtraInfo.setText(extraInfo);
                ...
}

 Use with after :   $ Instead of item
override fun onBindViewHolder(holder: ViewHolder, position: Int){
   val item = getItem(position)?: return
   with(item){
      holder.tvNewsTitle.text = StringUtils.trimToEmpty(titleEn)
           holder.tvNewsSummary.text = StringUtils.trimToEmpty(summary)
           holder.tvExtraInf.text = " difficulty :$gradeInfo |  Number of words :$length |  Journal entry : $numReviews"
       ...   
   }
}

3、run Applicable scenarios of function

Apply to let,with Function any scenario . because run The function is let,with A combination of two functions , To be precise, it makes up for let The function must use... In the body of the function it Parameter substitution object , stay run Functions can look like with Functions can also be omitted , Directly access the public properties and methods of the instance , On the other hand, it makes up for with Function input object null problem , stay run Functions can look like let Function to do the same empty processing .

run Before using the function :

override fun onBindViewHolder(holder: ViewHolder, position: Int){
   val item = getItem(position)?: return
   with(item){
           holder.tvNewsTitle.text = StringUtils.trimToEmpty(titleEn)
           holder.tvNewsSummary.text = StringUtils.trimToEmpty(summary)
           holder.tvExtraInf = " difficulty :$gradeInfo |  Number of words :$length |  Journal entry : $numReviews"
       ...   
  
   }
}

Use run after :

override fun onBindViewHolder(holder: ViewHolder, position: Int){
  getItem(position)?.run{
      holder.tvNewsTitle.text = StringUtils.trimToEmpty(titleEn)
           holder.tvNewsSummary.text = StringUtils.trimToEmpty(summary)
           holder.tvExtraInf = " difficulty :$gradeInfo |  Number of words :$length |  Journal entry : $numReviews"
       ...   
   }
}

4、apply Applicable scenario

Overall function and run The function is very similar to , The only difference is that the value it returns is the object itself , and run A function is a closure that returns , Returns the value of the last line . It is based on this difference that its applicable scenarios are slightly different from run The function is a little different . apply It is generally used when an object instance is initialized , You need to assign values to the properties in the object . Or dynamic inflate a XML Of View You need to give View Binding data also uses , This kind of situation is very common . Especially in our development, there will be some data model towards View model In the process of transformation instantiation, we need to use .

Not used apply The code for the function looks like this :

mSheetDialogView = View.inflate(activity, R.layout.layout_sheet_inner, null)
mSheetDialogView.course_comment_tv_label.paint.isFakeBoldText = true
mSheetDialogView.course_comment_tv_confirm.paint.isFakeBoldText = true
mSheetDialogView.course_comment_seek_bar.max = 10
mSheetDialogView.course_comment_seek_bar.progress = 0

Use apply The code after the function is like this :

mSheetDialogView = View.inflate(activity, R.layout.layout_sheet_inner, null).apply{
   course_comment_tv_label.paint.isFakeBoldText = true
   course_comment_tv_score.paint.isFakeBoldText = true
   course_comment_seek_bar.max = 10
   course_comment_seek_bar.progress = 0
}

Multiple levels of judgment :

if (mSectionMetaData == null || mSectionMetaData.questionnaire == null || mSectionMetaData.section == null) {
       return;}
       if (mSectionMetaData.questionnaire.userProject != null) {
             renderAnalysis();
             return;}
             if (mSectionMetaData.section != null) {
                   fetchQuestionData();
                   return;}

apply After optimization :

mSectionMetaData?.apply{
     //mSectionMetaData Operate when not empty mSectionMetaData
}?.questionnaire?.apply{
    //questionnaire Operate when not empty questionnaire
}?.section?.apply{
     //section Operate when not empty section
}?.sectionArticle?.apply{
    //sectionArticle Operate when not empty sectionArticle
}

Four 、DSL( Domain specific languages )

There is only one parameter , And use infix Modified function

// book 
class Book{
    //infix  Infix expressions for custom operators . Ben didn't on, Customize a , No class name is required . Method to call 
    // Pass in any type of , Return to one Boolean Parameters of type 
    infix fun on(any: Any): Boolean{
        return true
    }
}
// Table 
class Desk

fun main(args: Array<String>) {
    if(Book() on Desk()){
        println(" The book is on the desk ")
    }
}

5、 ... and 、 Closure

kotlin Closure of learning notes

原网站

版权声明
本文为[User 9854323]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206251146400693.html

随机推荐