代码之家  ›  专栏  ›  技术社区  ›  Dishonered

Kotlin-如何消除此编译器错误?

  •  -1
  • Dishonered  · 技术社区  · 7 年前

    我有这个班

    data class Properties( val actionBarColor : Int , val fileName : String) : 
     Serializable{
    var title : String = ""
    var readModeOnly : Boolean = false
    }
    

    这个假设条件

    var properties = Properties()
    
    if(properties?.readModeOnly){
    
    }
    

    但是编译器说,必需的 Boolean 建立 Boolean? . 我该怎么做才能成功?我不想它是无效的。

    2 回复  |  直到 7 年前
        1
  •  2
  •   zsmb13    7 年前

    你只需要 safe call operator ?. 如果左侧是可空类型。在这种情况下, properties 不可为空(其类型为 Properties 而不是 Properties? ,所以你可以让接线员离开,进入 readModeOnly 直接属性:

    var properties = Properties()
    
    if (properties.readModeOnly) {
    
    }
    

    按以下注释更新:

    如果 性质 那么,可以为空 properties?.readModeOnly 将返回 Boolean? (因为它会回来 null 如果 性质 本身就是 无效的 )。这意味着表达式现在可以计算为三个值: true , false 无效的 .

    如果你考虑 无效的 成为 ,你可以用这个 if 检查:

    if (properties?.readModeOnly == true) {
    
    }
    

    或如果 无效的 被考虑 ,尽管这似乎违反直觉:

    if (properties?.readModeOnly != false) {
    
    }
    
        2
  •  0
  •   Saudaggel    7 年前

    试用使用 ?.let{}

    properties?.let {
        val readModeOnly = it.readModeOnly
        ...
    }