Newyorkcity
V2EX  ›  问与答

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

  •  
  •   Newyorkcity · May 26, 2021 · 2119 views
    This topic created in 1812 days ago, the information mentioned may be changed or developed.
    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 replies    2021-05-26 11:38:22 +08:00
    timethinker
        1
    timethinker  
       May 26, 2021   ❤️ 1
    没有用过 kotlin,不过看似这个东西在语言层面有点类似于 C/C++的结构体?那么正确的做法应该使用组合而不是继承吧。

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

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

    主构造函数需要至少有一个参数;
    主构造函数的所有参数需要标记为 val 或 var ;
    数据类不能是抽象、开放、密封或者内部的;
    (在 1.1 之前)数据类只能实现接口。
    secretman
        5
    secretman  
       May 26, 2021   ❤️ 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.
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4103 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 68ms · UTC 00:05 · PVG 08:05 · LAX 17:05 · JFK 20:05
    ♥ Do have faith in what you're doing.