一些实用的函数
rangeTo()
rangeTo()
函数仅仅是调用
*Range
的构造函数,比如:
138
Ranges
class
Int
{
fun
rangeTo
(other: Byte)
: IntRange =
IntRange
(this, Other)
fun
rangeTo
(other: Int)
: IntRange =
IntRange
(this, other)
}
downTo()
downTo()
扩展函数可以为任何数字类型定义,这里有俩个例子:
fun Long
.
downTo
(other: Double)
: DoubleProgression {
return
DoubleProgression(this, other,
-1.0
)
}
fun Byte
.
downTo
(other: Int)
: IntProgression {
return
IntProgression(this, other,
-1
)
}
reversed()
reversed()
扩展函数是给所有的
*Range
和
*Progression
类定义的,并且
它们都返回反向的级数。
fun
IntProgression.
reversed
()
: IntProgression {
return
IntProgression(end, start, -increment)
}
fun
IntRange.
reversed
()
: IntProgression {
return
IntProgression(end, start,
-1
)
}
step()
step()
扩展函数是给所有的
*Range
和
*Progression
类定义的,所有的返
回级数都修改了
step
值。注意
step
值总是正的,否则函数不会改变迭代的方向。
139
Ranges
fun
IntProgression.
step
(step: Int)
: IntProgression {
if
(step <= 0) throw IllegalArgumentException("Step must be po
sitive, was: $step")
return IntProgression(start, end, if (increment >
0
) step
else
-step)
}
fun
IntRange.
step
(step: Int)
: IntProgression {
if
(step <= 0) throw IllegalArgumentException("Step must be po
sitive, was: $step")
return IntProgression(start, end, step)
}
140
类型检查和自动转换
类型检查和转换
is !is
表达式
我们可以在运行是通过上面俩个操作符检查一个对象是否是某个特定类:
if
(obj
is
String) {
print(obj.length)
}
if
(obj !
is
String) {
// same as !(obj is String)
print(
"Not a String"
)
}
else
{
print(obj.length)
}
智能转换
在很多情形中,需要使用非明确的类型,因为编译器会跟踪
is
检查静态变量,
并在需要的时候自动插入安全转换:
fun
demo
(x: Any)
{
if
(x
is
String) {
print(x.length)
// x is automatically cast to String
}
}
编译器足够智能如何转换是安全的,如果不安全将会返回:
if
(x !
is
String)
return
print(x.length)
//x
自动转换为
String
或者在
|| &&
操作符的右边的值
141
类型检查和自动转换
// x is automatically cast to string on the right-hand side of
`||`
if
(x !
is
String || x.length ==
0
)
return
// x is automatically cast to string on the right-hand side of
`&&`
if
(x
is
String && x.length >
0
)
print(x.length)
// x is automatically cast to String
这样的转换在
when
表达式和
whie
循环中也会发生
when
(x) {
is Int
-> print(x +
1
)
is
String -> print(x.length +
1
)
is
Array<Int> -> print(x.sum())
}