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

Kotlin-如何修复所需类型的类型不匹配

  •  0
  • Leff  · 技术社区  · 3 年前

    我有一堆bean,它们具有如下可为null的属性:

    package myapp.mybeans;
    
    data class Foo(val name : String?);
    

    我在全局空间中有一个方法,如下所示:

    package myapp.global;
    
    public fun makeNewBar(name : String) : Bar
    {
      ...
    }
    

    在其他地方,我需要做一个 Bar 从里面的东西 Foo 。所以,我这样做:

    package myapp.someplaceElse;
    
    public fun getFoo() : Foo? { }
    ...
    val foo : Foo? = getFoo();
    
    if (foo == null) { ... return; }
    
    
    // I know foo isn't null and *I know* that foo.name isn't null
    // but I understand that the compiler doesn't.
    // How do I convert String? to String here? if I do not want
    // to change the definition of the parameters makeNewBar takes?
    val bar : Bar = makeNewBar(foo.name);
    

    此外,在这里使用进行一些转换 foo.name 每次都要用每一件小事来清理它,同时一方面为我提供编译时间的保证和安全性,这在大多数时候都是一个很大的麻烦。有没有办法避开这些情况?

    0 回复  |  直到 8 年前
        1
  •  53
  •   miensol    8 年前

    你需要这样的双感叹号:

    val bar = makeNewBar(foo.name!!)
    

    如中所述 Null Safety section :

    第三种选择是NPE爱好者。我们可以写b!!,这将 返回b的非null值(例如,在我们的示例中为String)或throw 如果b为空,则为NPE:

    val l = b!!.length 
    

    因此,如果你想要一个NPE,你可以拥有它,但你必须明确地要求它,而且它不会出现在 蓝色

        2
  •  6
  •   Sir Codesalot    4 年前

    您可以使用扩展名:

    fun <T> T?.default(default: T): T {
        return this ?: default
    }
    

    然后这样使用:

    fun getNonNullString(): String {
        return getNullableString().default("null")
    }