正如Tom所说,您的编译器对类型一无所知。你需要做这样一个简单的演员阵容:
我正在摆弄Kotlin,并试图创建一个简单的生物层次。我似乎已经能够成功地做到这一点,然而,我无法访问我的"头:附件"类中的"思考"方法,该类是人类:生物类的子类
我可以看到子类一直打印到头类,但我无法运行think((方法
val human = Human()
println(human.appendages["Head"]) // [Head@3803641]
println(human.appendages["Head"]?.get(0)) // Head@3803641
human.appendages["Head"]?.get(0).think() // uncaught reference
import org.omg.CORBA.Object
import java.util.*
open class Creature {
var appendages = HashMap<String,ArrayList<Appendage>>()
}
open class Appendage {
constructor() {}
}
open class Human : Creature {
constructor()
{
appendages["Arm"] = ArrayList<Appendage>()
appendages["Arm"]?.add(Arm())
appendages["Arm"]?.add(Arm())
appendages["Leg"] = ArrayList<Appendage>()
appendages["Leg"]?.add(Leg())
appendages["Leg"]?.add(Leg())
appendages["Head"] = ArrayList<Appendage>()
appendages["Head"]?.add(Head("Human"))
}
}
class Alien : Creature
{
constructor()
{
appendages["Tentacle"] = ArrayList<Appendage>()
appendages["Tentacle"]?.add(Tentacle())
appendages["Tentacle"]?.add(Tentacle())
appendages["Tentacle"]?.add(Tentacle())
appendages["Tentacle"]?.add(Tentacle())
appendages["Arm"] = ArrayList<Appendage>()
appendages["Arm"]?.add(Arm())
appendages["Arm"]?.add(Arm())
appendages["Leg"] = ArrayList<Appendage>()
appendages["Leg"]?.add(Leg())
appendages["Leg"]?.add(Leg())
appendages["Head"] = ArrayList<Appendage>()
appendages["Head"]?.add(Head("Alien"))
appendages["Head"]?.add(Head("Alien"))
}
}
class Head : Appendage {
private var whatami : String = ""
constructor(whatami : String)
{
this.whatami = whatami
}
public fun think()
{
println("$whatami Thinking")
}
}
open class Arm : Appendage {
private var rotation = mutableListOf<Int>(0,0,0)
constructor() {}
fun rotateX(degrees: Int)
{
rotation[0] = degrees
}
fun rotateY(degrees: Int)
{
rotation[1] = degrees
}
fun rotateZ(degrees: Int)
{
rotation[2] = degrees
}
}
open class Leg : Appendage {
private var rotation = mutableListOf<Int>(0,0,0)
constructor() {}
fun rotateX(degrees: Int)
{
rotation[0] = degrees
}
fun rotateY(degrees: Int)
{
rotation[1] = degrees
}
fun rotateZ(degrees: Int)
{
rotation[2] = degrees
}
}
open class Tentacle : Appendage {
private var rotation = mutableListOf<Int>(0,0,0)
constructor() {}
fun rotateX(degrees: Int)
{
rotation[0] = degrees
}
fun rotateY(degrees: Int)
{
rotation[1] = degrees
}
fun rotateZ(degrees: Int)
{
rotation[2] = degrees
}
}
我希望程序打印"人类思维",但我收到了一个"未获取参考"错误
(human.appendages["Head"]?.get(0) as Head).think()