首页 > 其他分享 >Kotlin Notes - 2

Kotlin Notes - 2

时间:2023-11-16 16:36:53浏览次数:30  
标签:val Int Kotlin Notes interface fun age

  1. Properties in Kotlin classes can be declared either as mutable, using the var keyword, or as read-only, using the val keyword.

      // full syntax for declaring a property
      var <propertyName>[: <PropertyType>] [= <property_initializer>]
      [<getter>]
      [<setter>]
    
      // example
      var stringRepresentation: String
        get() = this.toString()
        set(value) {
            setDataFromString(value)
        }
    
  2. lateinit modifier can be used on var properties when dependency injection, or in the setup method of a unit test.

  3. An interface with only one abstract method is called a functional interface, or a Single Abstract Method (SAM) interface.

    fun interface IntPredicate {
       fun accept(i: Int): Boolean
    }
    
    // if don't use SAM interface, you will need to write code like this:
    // val isEven = object : IntPredicate {
    //   override fun accept(i: Int): Boolean {
    //       return i % 2 == 0
    //   }
    // }
    
    val isEven = IntPredicate { it % 2 == 0 }
    
    fun main() {
       println("Is 7 even? - ${isEven.accept(7)}")
    }
    
  4. There are four visibility modifiers in Kotlin: private, protected, internal(visible in the same module), and public. The default visibility is public.

  5. Kotlin provides the ability to extend a class or an interface with new functionality without having to inherit from the class or use design patterns such as Decorator. This is done via special declarations called extensions.

    fun MutableList<Int>.swap(index1: Int, index2: Int) {
      val tmp = this[index1] // 'this' corresponds to the list
      this[index1] = this[index2]
      this[index2] = tmp
    }
    
    val list = mutableListOf(1, 2, 3)
    list.swap(0, 2) // 'this' inside 'swap()' will hold the value of 'list'
    

    If a class has a member function, and an extension function is defined which has the same receiver type, the same name, and is applicable to given arguments, the member always wins.

    Kotlin supports extension properties much like it supports functions:

    val <T> List<T>.lastIndex: Int
        get() = size - 1
    

    By the way, it's better to define extensions on the top level, directly under packages

  6. Data classes in Kotlin are classes whose main purpose is to hold data. The compiler automatically derives the following members from all properties declared in the primary constructor

    data class User(val name: String, val age: Int)
    

    Component functions generated for data classes make it possible to use them in destructuring declarations:

    val jane = User("Jane", 35)
    val (name, age) = jane
    println("$name, $age years of age")
    // Jane, 35 years of age
    

标签:val,Int,Kotlin,Notes,interface,fun,age
From: https://www.cnblogs.com/otf-notes/p/17836280.html

相关文章

  • kotlin 泛型基础
    一、泛型函数如下是泛型函数的一种构造在fun函数标记的右边增加该函数要使用的类型形参fun<T>List<T>.slice(indices:IntArray):List<T>{valret=mutableListOf<T>()for(vinindices){ret.add(this[v])}returnret}listOf(3,4,5,6......
  • Kotlin委托的深入解析与实践
    引言在Kotlin编程语言中,委托是一项强大的特性,它能够极大地简化代码,提高代码的可维护性。本文将深入探讨Kotlin中的委托机制,介绍其原理、具体使用方式以及实际应用场景。委托的原理委托是一种通过将实际工作委托给其他对象来实现代码重用的机制。在Kotlin中,委托通过关键字by来实现......
  • Kotlin Notes - 1
    AclassinKotlinhasaprimaryconstructorandpossiblyoneormoresecondaryconstructors.//primaryconstructorclassPerson(valname:String){valchildren:MutableList<Person>=mutableListOf()//secondaryconstructorconstru......
  • kotlin 内联函数 inline
    一、当函数被声明为内联函数(函数的前缀增加inline),那么函数体会被直接替换到函数被声明的地方,而不是被正常的调用。如下的代码inlinefunsynchronized(lock:Lock,action:()->Unit){lock.lock()try{returnaction()}finally{lock.unlo......
  • kotlin 高阶函数
    一、定义:以另一个函数作为参数或者返回值的函数1、kotlin中,函数以lambda或者函数引用来表示 二、函数类型1、如下是函数的类型上述声明了函数的类型,括号内包含了该函数类型需要传入的参数类型,紧接着箭头,最后是返回的类型(在声明函数类型时候,返回类型即使是Unit也不可以省略)......
  • 一文快速实战Kotlin协程与Flow
    前言不知道大家有没有跟我一样的感受:即使自己用心在网上学过协程和Flow了,但过了一段时间就又忘掉了。这大部分的原因其实是因为我们缺少实战。我平时工作里根本就接触不到协程和Flow,自己又不敢硬往上写,万一出问题了咋整?所以一直就处于理论学习阶段,导致我学了就跟没学一样。今天就带......
  • 知乎问题采集如此轻松,Kotlin来帮忙
    知乎是国内最好的一个知识学习的平台,我们平时很多问题都能在知乎上找到很好的答案。那么今天我就用Kotlin编写一段知乎问题收集的程序,我们可以根据自己需要的问题,进行针对性的采集,非常的不错,一起来看看吧。```kotlinimportokhttp3.OkHttpClientimportokhttp3.Requestimportja......
  • Kotlin协程学习——协程的基本介绍
    我们为什么需要学习Kotlin协程呢?我们已经有了成熟的JVM库,比如RxJava或Reactor。此外,Java本身就支持多线程,很多人也选择使用普通的回调函数。很明显,我们已经有了很多选项来执行异步操作。Kotlin协程提供了更多的功能。它们是一个概念的实现,该概念最早在1963年被描述,但等待了多年才......
  • kotlin 重载运算符
    一、二元运算符的重载1、常见的运算符有:加、减、乘、除、求余;我们要重载这些运算符的操作这里以加法重载运算符为例dataclassPoint(valx:Int,valy:Int){operatorfunplus(other:Point):Point{returnPoint(x+other.x,y+other.y)}}如上......
  • Kotlin-嵌套类_内部类_匿名内部类
    Kotlin-嵌套类&内部类&匿名内部类1.嵌套类类可以被嵌套在其它类中:classOuter{privatevalbar:Int=1classNested{funfoo(){println("fooinOuter#Nested#foo()")}funtest(){//println("Ne......