我有这行代码:
if (x * y * z > maxProduct) maxProduct = x * y * z
Run Code Online (Sandbox Code Playgroud)
但我的问题是,当我想像这样使用它时,我必须写x * y * z两次。我知道我可以在语句之前创建一个变量if,如下所示:
val product = x * y * z
if (product > maxProduct) maxProduct = product
Run Code Online (Sandbox Code Playgroud)
但我不喜欢必须创建一个仅用于此表达式的临时变量。有没有办法改进我的代码?
我有一个
class Foo {
lateinit var property1: String
lateinit var property2: Int
lateinit var property3: Long
}
Run Code Online (Sandbox Code Playgroud)
那么是否可以在这样的函数中传递类的属性?
fun bar(fooProperty: FooProperty) {
println(
when(fooProperty) {
Foo.property1 -> "Property1"
Foo.property2 -> "Property2"
Foo.property3 -> "Property3"
}
)
}
Run Code Online (Sandbox Code Playgroud)
然而,这是无效的代码。我只是想知道这是否可以实现。
我很好奇为什么 KotlinSet有索引。您可以使用 来访问元素mySet.elementAt(index)。我所知道的其他语言都没有这个功能。如果集合不应该排序但它们有索引,那么该功能是否有用?另外,这个特性难道不会使得SetKotlin 中的 s 比Set其他语言中的其他 s 慢吗?
如果我有一个 python 生成器函数,我们就说这个:
def gen():
x = 0
while (true):
yield x
x += 1
Run Code Online (Sandbox Code Playgroud)
该函数会记住其当前状态,每次调用时gen()都会产生一个新值。本质上,我想要一个能够记住其状态的 Kotlin 序列。
kotlin ×4
arguments ×1
generator ×1
generics ×1
if-statement ×1
optimization ×1
properties ×1
python ×1
sequence ×1
set ×1
variables ×1
yield ×1