You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin出现Classifier 'Child'无companion object需在此处初始化报错咨询

报错信息

Classifier 'Child' does not have a companion object, and thus must be initialized here

问题产生原因
  • 错误出现在main函数的变量声明行:你使用了Java风格的类名 变量名 = 实例的变量声明语法,不符合Kotlin的语法规范。
  • Kotlin要求所有变量声明必须以val(只读变量)或var(可变变量)关键字开头,你直接写Child child = Child()时,编译器会将开头的Child识别为类引用,默认尝试读取该类伴生对象下的child属性,而你的Child类未定义伴生对象,因此触发该报错。
修复方案

将main函数里的变量声明改为Kotlin合法语法即可,支持两种写法:

  1. 类型自动推断写法:
val child = Child()
  1. 显式声明变量类型写法:
val child: Child = Child()
修复后完整可运行代码
open class Parent constructor (name: String){
    val parentName: String = name
}
class Child : Parent("Amit"){
    fun printName(){
        print(parentName)
    }
}
fun main(agrs: Array<String>) {  
    val child = Child()
    child.printName()
}

内容的提问来源于stack exchange,提问作者Amit Yadav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 07:06:05