仅当输入不为空时如何使用kotlin的默认参数?

Lou*_*sai 7 kotlin

例子:

data class Something(val mendatory: String = "default value")

val userInput: String? by SomeTypeOfInputFieldThatReturnsNullable

//val something = Something(userInput)    //not valid because userInput is String?

val something = if (userInput == null) 
                    Something() 
                else 
                    Something(userInput)
Run Code Online (Sandbox Code Playgroud)

是否有一些不太详细的方法告诉 kotlin 仅在参数不为空时传递参数?

Rol*_*and 3

取决于你所说的不那么冗长是什么意思。

一种方法是使用null-safe-operator ( ?.)let

val something = userInput?.let(::Something) 
                         ?: Something()
Run Code Online (Sandbox Code Playgroud)

我让你自己决定这是否真的不那么冗长。

另一种变体基本上只是将null- 值传递给data class. 通过提供适当的构造函数或通过适当的工厂函数来实现。以下只是众多变体之一(现在使用Companioninvoke):

data class Something(val mandatory: String) {
  companion object {
    operator fun invoke(s : String? = null) = Something( s ?: "default value")
  }
}
Run Code Online (Sandbox Code Playgroud)

然后调用它看起来像:

val something = Something(userInput) // if userInput is String? the companion function is called... if it's String, the constructor is used

// or also using invoke:
val something = Something() // now with s = null, leading to "default value"
Run Code Online (Sandbox Code Playgroud)