Kotlin中data class构造函数的问题

clipboard.png

Mybatis 报错说找不到
yc.ycjz.entity.Child matching [java.lang.Long, java.lang.Long]
这个构造函数是什么原因啊?

阅读 13.8k
4 个回答

data class 除非全部提供默认值,否则是没有空构造函数的,而MyBatis映射成对象的时候是通过反射拿空构造函数,拿不到就会报错。
使用kotlin提供的kotlin noarg plugin可以解决,使用方法参考:https://kotlinlang.org/docs/r...

新手上路,请多包涵

你没有把那两个Long初始化吧。

如果构造函数是无参的,就会用默认的参数给属性赋值。

NOTE: On the JVM, if all of the parameters of the primary constructor have default values, the compiler will generate an additional parameterless constructor which will use the default values. This makes it easier to use Kotlin with libraries such as Jackson or JPA that create class instances through parameterless constructors.

class Customer(val customerName: String = "")
参见:
https://huanglizhuo.gitbooks....
http://kotlinlang.org/docs/re...

我自己也是刚刚开始学,如果说错了请指正,谢谢。

data class 的声明是 Long,从上面代码上来也就可能是 kotlin.Long
那这个 kotlin.Long 在生成 JVM 代码时,有可能是 long 也可能是 java.lang.Long
从上面的错误来看,应该是生成了 long 类型.
所以 你可以将 Long 声明指定声明为 java.lang.Long

data class Child(
        var stuId: Long? = null,
        var schoolId: Long? = null,
        var stuName: String? = "",
        var stuAvatar: String? = ""
)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进