您好,是否可以像在 python 中一样在 Kotlin 函数中传递范围?我刚刚开始学习 Kotlin,但我有点卡住了
我希望我能通过类似的东西
my_gauge = Gauge('test_name',1..200, 201..300, and etc.)
Run Code Online (Sandbox Code Playgroud)
例如我有一个在底座上旋转的仪表对象
class Gauge(val gauge_name: String,
val red_value: Float,
val orange_value: Float,
val yellow_value: Float,
val green_value: Float,
var current_value: Float,
val min_value: Float,
val max_value: Float) {
val gauge_green = 0xFF66C2A5.toInt()
val gauge_yellow = 0xFFFDD448.toInt()
val gauge_orange = 0xFFF5A947.toInt()
val gauge_red = 0xFFD53E4F.toInt()
val min_rotation: Int = 0;
val max_rotation: Int = 300;
val ratio = max_rotation / max_value;
fun calculate_rotation(): Int {
return (current_value * ratio).toInt()
}
fun get_color(): Int {
if (current_value >= red_value) {
return gauge_red
}
if (current_value > orange_value) {
return gauge_orange
}
if (current_value > yellow_value) {
return gauge_yellow
}
return gauge_green
}
}
Run Code Online (Sandbox Code Playgroud)
我刚刚意识到它不适用于这些数据,相反,最好围绕范围构建我的逻辑
所以我的问题是如何在类/函数中将范围作为参数传递(而不是浮点数)
PS:该函数get_colors不正确,一旦我可以使用when(current_value)语句传递范围,我将修复它
是的,产生的范围类型..是ClosedRange<T>:
fun foo(floatRange: ClosedRange<Float>) {
println(floatRange.random())
}
// Usage:
foo(1f..10f)
Run Code Online (Sandbox Code Playgroud)
对于整数范围,您可能更喜欢IntRangeover ClosedRange<Int>,因为它允许您通过使用firstandlast而不是startand来使用它,而不会产生装箱的性能成本endInclusive。其他号码类型没有未装箱的版本。
小智 5
以简单的方式尝试一下,您可以根据数据类型 IntRange、FloatRange、LongRange 等使用范围。
fun foo(range: IntRange){
for (a in range){
println(a)
}
}
Run Code Online (Sandbox Code Playgroud)
// 通过 foo(1..10) 调用该函数
| 归档时间: |
|
| 查看次数: |
1680 次 |
| 最近记录: |