我无法弄清楚?:例如这种情况
val list = mutableList ?: mutableListOf()
Run Code Online (Sandbox Code Playgroud)
为什么可以修改它
val list = if (mutableList != null) mutableList else mutableListOf()
Run Code Online (Sandbox Code Playgroud) 解释:这个问题更多的是关于Kotlin的设计意图.许多表达式语言都支持Ternary operator和if expression[例如,Ruby,Groovy.]
首先,我知道Groovy支持Ternary operator和Elvis operator:Groovy中的三元运算符.所以我不认为这是一个语法问题.
然后官方文件说:
在Kotlin中,if是一个表达式,即它返回一个值.因此没有三元运算符(condition?then:else),因为普通的if在这个角色中工作正常.
这并不能说服我.因为Kotlin支持Elvis operator哪个普通如果在那个角色也可以正常工作.
我觉得ternary operator有时候比平常更好if,不过我想知道Kotlin为什么不支持ternary operator?
所以在java中我们有三元运算符(?),它有时很容易通过if-else内联计算一些值.例如:
myAdapter.setAdapterItems(
textToSearch.length == 0
? noteList
: noteList.sublist(0, length-5)
)
Run Code Online (Sandbox Code Playgroud)
我知道kotlin中的等价物是:
myAdapter.setAdapterItems(
if(textToSearch.length == 0)
noteList
else
noteList.sublist(0, length-5)
)
Run Code Online (Sandbox Code Playgroud)
但我曾经习惯于喜欢Java中的三元运算符,用于短表达式条件,以及将值传递给方法时.有没有Kotlin等价物?
我可以用Java编写
int i = 10;
String s = i==10 ? "Ten" : "Empty";
Run Code Online (Sandbox Code Playgroud)
即使我可以在方法参数中传递它。
callSomeMethod(i==10 ? "Ten" : "Empty");
Run Code Online (Sandbox Code Playgroud)
如何将其转换为Kotlin?在Kotlin中编写相同内容时,Lint显示错误。
我有一个data class,我正在创建一个object。我传递这样的参数值:
val leadDetails = AddLeadDetails(AgentId = agent.UserId,
Name = leadUserName.text.toString().trim(),
MobileNo = leadMobileNumber.text.toString().trim(),
ProductType = productTypeId,
LoanType = productTypeItem,
ApplicationStatus = //if condition to put value i.e if(string == "s") "One value" else "Second Value"
Amount = productAmountText.text.toString().trim(),
Pincode = pinCodeText.text.toString().trim(),
Remarks = customerRemarks.text.toString().trim(),
Type = referType!!)
Run Code Online (Sandbox Code Playgroud)
ApplicationStatus我想根据条件添加一个值if。我怎样才能做到这一点?
如何将以下代码从 Java 转换为 Kotlin?
Boolean mBoolean = false
view.setVisibility(mBoolean ? View.VISIBLE : View.GONE);
Run Code Online (Sandbox Code Playgroud) 我有以下代码:
private fun setCashPaymentContainer(isSelected: Boolean) {
if (isSelected) {
dataBinding.cashPaymentCheckImageViewContainer.visibility = View.VISIBLE
} else {
dataBinding.cashPaymentCheckImageViewContainer.visibility = View.GONE
}
}
Run Code Online (Sandbox Code Playgroud)
它工作正常,但我想改进它并将它写成简化和可读的 if else 块。如果我能写一行 if else 语句会很好请建议。