在Kotlin有一个相当于Swift代码下面?
if let a = b.val {
} else {
}
在Kotlin有一个相当于Swift代码下面?
if let a = b.val {
} else {
}
当前回答
如果让我们使用内联的乐趣,我们可以得到像Swift一样的unwring语法
inline fun <T:Any?> T?.unwrap(callback: (T)-> Unit) : Boolean {
return if (this != null) {
this?.let(callback)
true
}else {
false
}
}
用途::
val name : String? = null
val rollNo : String? = ""
var namesList: ArrayList<String>? = null
if (name.unwrap { name ->
Log.i("Dhiru", "Name have value on it $name")
})else if ( rollNo.unwrap {
Log.i("Dhiru","Roll have value on it")
}) else if (namesList.unwrap { namesList ->
Log.i("Dhiru","This is Called when names list have value ")
}) {
Log.i("Dhiru","No Field have value on it ")
}
其他回答
下面是如何只在name不为空时执行代码:
var name: String? = null
name?.let { nameUnwrapp ->
println(nameUnwrapp) // not printed because name was null
}
name = "Alex"
name?.let { nameUnwrapp ->
println(nameUnwrapp) // printed "Alex"
}
在kotlin中也有类似的方法来实现Swift的if-let风格
if (val a = b) {
a.doFirst()
a.doSecond()
}
您还可以分配多个可空值
if (val name = nullableName, val age = nullableAge) {
doSomething(name, age)
}
如果可空值被使用超过1次,这种方法将更适合。在我看来,它从性能方面有所帮助,因为可为空的值将只检查一次。
来源:Kotlin Discussion
我添加这个答案是为了澄清已接受的答案,因为它太大了,不适合评论。
这里的一般模式是,你可以使用Kotlin中可用的范围函数的任何组合,由Elvis操作符分隔,如下所示:
<nullable>?.<scope function> {
// code if not null
} :? <scope function> {
// code if null
}
例如:
val gradedStudent = student?.apply {
grade = newGrade
} :? with(newGrade) {
Student().apply { grade = newGrade }
}
我的答案完全是抄袭别人的。但是,我不容易理解他们的表情。所以我想提供一个更容易理解的答案会很好。
迅速:
if let a = b.val {
//use "a" as unwrapped
}
else {
}
在芬兰湾的科特林:
b.val?.let{a ->
//use "a" as unwrapped
} ?: run{
//else case
}
让我们首先确保我们理解了所提供的Swift习语的语义:
if let a = <expr> {
// then-block
}
else {
// else-block
}
它的意思是:“如果<expr>结果为非nil可选,则输入then块,并将符号a绑定到未包装的值。否则进入else块。
特别注意,a只在then块内绑定。在Kotlin中,您可以通过调用很容易地得到这个
<expr>?.also { a ->
// then-block
}
你可以像这样添加一个else-block:
<expr>?.also { a ->
// then-block
} ?: run {
// else-block
}
这将导致与Swift习惯用法相同的语义。