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

Kotlin Notes - 5

时间:2023-11-27 23:37:45浏览次数:28  
标签:String val nullable Kotlin Notes length null

  1. In Kotlin, the type system distinguishes between references that can hold null (nullable references) and those that cannot (non-nullable references). For example, a regular variable of type String cannot hold null:

    var a: String = "abc" // Regular initialization means non-nullable by default
    a = null // compilation error
    

    To allow nulls, you can declare a variable as a nullable string by writing String?:

    var b: String? = "abc" // can be set to null
    b = null // ok
    print(b)
    
  2. Compiler can check for null in condition:

    val b: String? = "Kotlin"
    if (b != null && b.length > 0) {
       print("String of length ${b.length}")
    } else {
       print("Empty string")
    }
    
  3. Your second option for accessing a property on a nullable variable is using the safe call operator ?.:

    val a = "Kotlin"
    val b: String? = null
    println(b?.length)
    println(a?.length) // Unnecessary safe call
    

    This returns b.length if b is not null, and null otherwise. The type of this expression is Int?.

  4. When you have a nullable reference, b, you can say "if b is not null, use it, otherwise use some non-null value":

    val l: Int = if (b != null) b.length else -1
    

    Instead of writing the complete if expression, you can also express this with the Elvis operator ?::

    val l = b?.length ?: -1
    

    If the expression to the left of ?: is not null, the Elvis operator returns it, otherwise it returns the expression to the right. Note that the expression on the right-hand side is evaluated only if the left-hand side is null.

    Since throw and return are expressions in Kotlin, they can also be used on the right-hand side of the Elvis operator.

    fun foo(node: Node): String? {
        val parent = node.getParent() ?: return null
        val name = node.getName() ?: throw IllegalArgumentException("name expected")
        // ...
    }
    
  5. The not-null assertion operator (!!) converts any value to a non-nullable type and throws an exception if the value is null.

    val l = b!!.length
    
  6. Regular casts may result in a ClassCastException if the object is not of the target type. Another option is to use safe casts that return null if the attempt was not successful:

    val aInt: Int? = a as? Int
    

标签:String,val,nullable,Kotlin,Notes,length,null
From: https://www.cnblogs.com/otf-notes/p/17860815.html

相关文章

  • Kotlin协程系列(二)
    在进行业务开发时,我们通常会基于官方的协程框架(kotlinx.coroutines)来运用Kotlin协程优化异步逻辑,不过这个框架过于庞大和复杂,如果直接接触它容易被劝退。所以,为了我们在后续的学习中游刃有余,在使用官方给出的复合协程时能够胸有成竹,我们暂且抛开它,按照它的思路实现一个轻量......
  • Kotlin协程系列(一)
    一.协程的定义最近看了一本有关kotlin协程的书籍,对协程又有了不一样的了解,所以准备写一个关于kotlin协程系列的文章。言归正传,我们在学习一个新东西的时候,如果连这个东西"是什么"都回答不了,那么自然很难进入知识获取阶段的"为什么"和"怎么办"这两个后续环节了。因此,我们......
  • Java下跌,Kotlin闯进前15,后生可畏
    近年来,Android开发由Java转Kotlin似乎成为了一种潮流。谷歌甚至曾公开表示:“Android的开发将越来越以Kotlin为先。”当前,作为移动开发中Java的劲敌,Kotlin在Tiobe流行指数中表现强劲。根据TIOBE11月发布的编程语言排行榜,Kotlin以1.15%的占比位列第15,较之10月上升3位。而在今......
  • Kotlin Notes - 4
    Ahigher-orderfunctionisafunctionthattakesfunctionsasparameters,orreturnsafunction.fun<T,R>Collection<T>.fold(initial:R,combine:(acc:R,nextElement:T)->R):R{varaccumulator:R=initialfor(elem......
  • [题解]CF1899D Yarik and Musical Notes
    思路暴力化简公式题。假定\(b_{i}^{b_j}=b_{j}^{b_{i}}\)成立,那么有:\[2^{a_i\times2^{a_j}}=2^{a_j\times2^{a_i}}\\a_i\times2^{a_j}=a_j\times2^{a_i}\\\frac{a_i}{a_j}=\frac{2^{a_i}}{2^{a_j}}\\\frac{a_i}{a_j}=2^{a_i-a_j}\]因为\(\fra......
  • Kotlin Notes - 3
    Functionparameterscanhavedefaultvalues,whichareusedwhenyouskipthecorrespondingargument.Thisreducesthenumberofoverloads:funread(b:ByteArray,off:Int=0,len:Int=b.size,){/*...*/}Ifthelastargumentafterde......
  • 运用Kotlin开发Android应用的一些技巧
    今天的这篇文章带你学习使用Kotlin开发Android应用,并对比我们传统语言Java,让你真真切切的感受到他的美和优雅。配置项目gradle文件applyplugin:'com.android.application'applyplugin:'kotlin-android'applyplugin:'kotlin-android-extensions'dependencies{clas......
  • kotlin协程:一文搞懂各种概念
    前言使用kotlin协程已经几年了,可以说它极大地简化了多线程问题的复杂度,非常值得学习和掌握。此文介绍并梳理协程的相关概念:suspend、non-blocking、Scope、Job、CoroutineContext、Dispatchers和结构化并发。进入协程世界简而言之,协程是可以在其内部进行挂起操作的实例,是否支持......
  • Kotlin Notes - 2
    PropertiesinKotlinclassescanbedeclaredeitherasmutable,usingthevarkeyword,orasread-only,usingthevalkeyword.//fullsyntaxfordeclaringapropertyvar<propertyName>[:<PropertyType>][=<property_initializer>]......
  • 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......