匿名对象的kotlin访问属性 [英] kotlin access property of anonymous object
问题描述
如何访问匿名对象的对象的属性word
How do I access the property word
of the object of the anonymous object
fun main(args: Array<String>) {
val sentence = "this is a nice sentence"
val wordLengths: List<Any> = sentence.split(' ').map {
object {
val length = it.length
val word = it
}
}
wordLengths.forEach { it:Any -> println(it) }
}
推荐答案
您明确声明wordLengths
为List<Any>
,并且Any
没有word
或length
属性.您应该让Kotlin从map
推断类型.
You are explicitly declaring wordLengths
to be List<Any>
, and Any
doesn't have a word
or length
property. You should let Kotlin infer the type from map
.
fun main() {
val sentence = "This is a nice sentence"
val wordLengths = sentence.split(' ').map {
object {
val word = it
val length = it.length
}
}
wordLengths.forEach {
println("[${it.length}] ${it.word}")
}
}
如果计划在方法之外需要此对象,则应创建必要的类或使用现有的类(例如Pair
或String
本身).请参见对象表达式:
If you plan on needing this object outside of the method then you should create the necessary class or use an existing class (e.g. Pair
or String
itself). See Object expressions:
请注意,匿名对象只能在本地和私有声明中用作类型.如果您将匿名对象用作公共函数的返回类型或公共属性的类型,则该函数或属性的实际类型将是该匿名对象的声明的超类型;如果您未声明,则为
Any
任何超类型.添加到匿名对象中的成员将不可访问.
Note that anonymous objects can be used as types only in local and private declarations. If you use an anonymous object as a return type of a public function or the type of a public property, the actual type of that function or property will be the declared supertype of the anonymous object, or
Any
if you didn't declare any supertype. Members added in the anonymous object will not be accessible.
这篇关于匿名对象的kotlin访问属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!