如何在Kotlin中打印ClosedRange [英] How to print ClosedRange in Kotlin
问题描述
我正在学习Kotlin,并且试图不理解Ranges
I'm learning Kotlin , and I'm trying to undetstand Ranges
我如下创建了String
范围
val alpha = "A".."Z"
我要为我写的内容打印
for (item in alpha) println(item)
但是它给出了错误
错误:(13,18)Kotlin:For循环范围必须具有'iterator()'方法
Error:(13, 18) Kotlin: For-loop range must have an 'iterator()' method
任何人都可以帮忙,如何打印此范围?
Can anyone help, how to print this range?
推荐答案
好吧,默认情况下您无法使用String
做到这一点,因为对于ClosedRange<String>
没有iterator()
,但是Char
可以工作直接:
Well you can't do it with String
s by default, since there's no iterator()
for ClosedRange<String>
, but Char
s will work directly:
val r = 'A'..'Z'
r.forEach(::println)
它将是CharRange
类型,并提供所需的iterator()
.
It will be of type CharRange
and provide the needed iterator()
.
要使非常特殊的示例与String
一起使用,可以定义自己的扩展函数并将其委托给Iterator<Char>
:
To make your very special example work with String
s, you could define your own extension function and delegate to a Iterator<Char>
:
operator fun ClosedRange<String>.iterator(): Iterator<String> {
val charIt = (start.toCharArray().first()..endInclusive.toCharArray().first()).iterator()
return object : Iterator<String> {
override fun hasNext() = charIt.hasNext()
override fun next(): String = charIt.nextChar().toString()
}
}
现在它可以按您的意愿工作了.但是请注意,对于大多数String
范围的用例,这没有意义.
Now it works as you wished. But be aware that this does not make sense for most use cases with ranges of String
.
这篇关于如何在Kotlin中打印ClosedRange的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!