V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
Newyorkcity
V2EX  ›  问与答

kotlin 不允许 data class 作为父类是不是限制得有点太严格了?

  •  
  •   Newyorkcity · 2021-05-26 10:20:05 +08:00 · 1390 次点击
    这是一个创建于 1069 天前的主题,其中的信息可能已经有所发展或是发生改变。
    data class Person(val name:String,val age:Int);
    data class Student(val name:String,val age:Int,val sid:Long);
    

    如果允许继承的话可以少写 val name:String,val age:Int 而且这里也确实存在父子类对应的逻辑关系啊。 另外如果在业务里还有 Teacher,Doctor……之类很多的话,重复的代码也就更多了。

    不太理解这一限制

    5 条回复    2021-05-26 11:38:22 +08:00
    timethinker
        1
    timethinker  
       2021-05-26 10:39:46 +08:00   ❤️ 1
    没有用过 kotlin,不过看似这个东西在语言层面有点类似于 C/C++的结构体?那么正确的做法应该使用组合而不是继承吧。

    如果确实有继承的需求,那么为何不直接用 class 呢?子类行为可以复用 /改写父类行为,实现多态的效果,这才是使用继承的主要原因吧。因为最终还是跑在 JVM 上,个人猜测这里不允许继承可能是因为 equals 或者 hashcode 可能会出现问题?
    hello1996
        2
    hello1996  
       2021-05-26 10:47:12 +08:00
    不用纠结,不用就好了,data class 纯属鸡肋
    timethinker
        3
    timethinker  
       2021-05-26 10:48:06 +08:00   ❤️ 1
    查到了文档,楼主可以参考一下: https://kotlinlang.org/docs/whatsnew11.html#sealed-and-data-classes
    secretman
        4
    secretman  
       2021-05-26 11:34:06 +08:00
    官方:

    为了确保生成的代码的一致性以及有意义的行为,数据类必须满足以下要求:

    主构造函数需要至少有一个参数;
    主构造函数的所有参数需要标记为 val 或 var ;
    数据类不能是抽象、开放、密封或者内部的;
    (在 1.1 之前)数据类只能实现接口。
    secretman
        5
    secretman  
       2021-05-26 11:38:22 +08:00   ❤️ 1
    Stack Overflow 高分答案:

    The truth is: data classes do not play too well with inheritance. We are considering prohibiting or severely restricting inheritance of data classes. For example, it's known that there's no way to implement equals() correctly in a hierarchy on non-abstract classes.

    So, all I can offer: don't use inheritance with data classes.
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3602 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 04:33 · PVG 12:33 · LAX 21:33 · JFK 00:33
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.