kotlin基础08

一些实用的函数
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())
}
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值