是否可以使以下代码在 Kotlin 中编译?
val variable: String? = "string"
val (a, b) = variable?.run {
1 to 2
}
Run Code Online (Sandbox Code Playgroud) 我想使用kubectl wait命令等待 pvc 被绑定。
我尝试kubectl wait --for=condition=bound pvc/my-pvc-claim --timeout=2s使用已经绑定的 PVC,但似乎不起作用。这是输出error: timed out waiting for the condition on persistentvolumeclaims/my-pvc-claim。
我阅读了kubectl wait文档,但仍然不明白我应该使用哪个条件。我怎样才能做到这一点?是否有更完整的文档解释如何做到这一点?
我正在尝试将值传递给构造函数并打印值。
open class Car(c: Int){
open var cost: Int = c
init {
println("This comes First $cost")
}
}
open class Vehicle(cc: Int) : Car(cc) {
override var cost: Int = 20000
init {
println("This comes Second $cost")
}
fun show(){
println("cost = $cost")
}
}
fun main() {
var vehicle = Vehicle(1000)
vehicle.show()
}
Run Code Online (Sandbox Code Playgroud)
输出
This comes First 0
This comes Second 20000
cost = 20000
Run Code Online (Sandbox Code Playgroud)
如果我只是评论这一行
override var cost: Int = 20000
输出将是
This comes First 1000
This …Run Code Online (Sandbox Code Playgroud) 考虑以下代码:
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.*
fun main() = runBlocking<Unit> {
val channel = Channel<String>()
launch {
channel.send("A1")
channel.send("A2")
log("A done")
}
launch {
channel.send("B1")
log("B done")
}
launch {
for (x in channel) {
log(x)
}
}
}
fun log(message: Any?) {
println("[${Thread.currentThread().name}] $message")
}
Run Code Online (Sandbox Code Playgroud)
原始版本的接收器协程如下:
launch {
repeat(3) {
val x = channel.receive()
log(x)
}
}
Run Code Online (Sandbox Code Playgroud)
它预计通道中只有 3 条消息。如果我将其更改为第一个版本,那么我需要在所有生产者协程完成后关闭通道。我怎样才能做到这一点?
我知道代码C与代码A相同。
我希望在代码B中使用该变量,aa而不是it在代码中,但这会导致错误。
为什么代码B与代码A不同?
代码A
private var aa:String?=null
aa?.let{
print(it.length)
}
Run Code Online (Sandbox Code Playgroud)
代码B
private var aa:String?=null
aa?.let{
print(aa.length)
}
Run Code Online (Sandbox Code Playgroud)
代码C
private var aa:String?=null
aa?.let{
aa-> print(aa.length)
}
Run Code Online (Sandbox Code Playgroud) 我尝试执行以下操作:
val a: Int? = 1
val b: Int? = 1
a?.plus(b)
Run Code Online (Sandbox Code Playgroud)
但它不会编译,因为plus需要一个Int.
我还尝试创建一个 biLet 函数:
fun <V1, V2, V3> biLet(a: V1?, b: V2?, block: (V1, V2) -> V3): V3? {
return a?.let {
b?.let { block(a, b) }
}
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用它:
val result = biLet(a, b) { p1, p2 -> p1 + p2 }
Run Code Online (Sandbox Code Playgroud)
但对于看似简单的事情来说,似乎需要做很多工作。有没有更简单的解决方案?
在 Kotlin 中,可以对 Map 使用方括号表示法,因此以下代码:
val mapOfMap: Map<String, Map<String, String>> = mapOf("Key1" to mapOf("Subkey1" to "Value1", "Subkey2" to "Value2"))
println(mapOfMap["Key1"])
Run Code Online (Sandbox Code Playgroud)
印刷:
{Subkey1=Value1, Subkey2=Value2}
Run Code Online (Sandbox Code Playgroud)
那太棒了。但为什么我不能执行以下操作
println(mapOfMap["Key1"]["Subkey1"])
Run Code Online (Sandbox Code Playgroud)
它会导致编译错误:在 Map 类型的可空接收器上只允许安全 (?.) 或非空断言 (!!.) 调用?
处理这个问题的正确方法是什么?
kotlin ×6
nullable ×2
android ×1
constructor ×1
hashmap ×1
inheritance ×1
java ×1
kotlinx.coroutines.channels ×1
kubectl ×1
kubernetes ×1
overriding ×1