小编Dj *_*shi的帖子

是否可以在 Kotlin 中的“if”条件内声明变量?

我有这行代码:

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)

但我不喜欢必须创建一个仅用于此表达式的临时变量。有没有办法改进我的代码?

variables optimization if-statement kotlin

7
推荐指数
2
解决办法
9602
查看次数

是否可以在 Kotlin 中将类属性作为函数参数传递?

我有一个

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)

然而,这是无效的代码。我只是想知道这是否可以实现。

generics arguments properties kotlin

2
推荐指数
1
解决办法
232
查看次数

为什么 Kotlin Sets 有索引?

我很好奇为什么 KotlinSet有索引。您可以使用 来访问元素mySet.elementAt(index)。我所知道的其他语言都没有这个功能。如果集合不应该排序但它们有索引,那么该功能是否有用?另外,这个特性难道不会使得SetKotlin 中的 s 比Set其他语言中的其他 s 慢吗?

set kotlin

2
推荐指数
1
解决办法
1658
查看次数

Python 生成器在 Kotlin 中的等价物是什么?

如果我有一个 python 生成器函数,我们就说这个:

def gen():
    x = 0
    while (true):
        yield x
        x += 1
Run Code Online (Sandbox Code Playgroud)

该函数会记住其当前状态,每次调用时gen()都会产生一个新值。本质上,我想要一个能够记住其状态的 Kotlin 序列。

python yield generator sequence kotlin

2
推荐指数
1
解决办法
1713
查看次数