-1

Given the following classes

abstract class SomeAbstractClass { abstract val name: String }
data class DataClass( override val name: String ) : SomeAbstractClass()
class NoDataClass( override val name: String ) : SomeAbstractClass()

For any instance of SomeAbstractClass, can I determine whether it is a data class without relying on type checking?

Some background: this seemed the best way of combining inheritance and data classes to me, as suggested in a different answer. Now, within the initializer block of SomeAbstractClass, I want to throw an exception in case the derived type is not a data class to ensure 'correct' (immutable) implementations of derived types.

Steven Jeuris
  • 18,274
  • 9
  • 70
  • 161
  • 5
    Note that data classes can still have var members. – Oliver Charlesworth Dec 12 '17 at 10:38
  • Also, as an anecdote, I often find myself needing to create non-data-class subtypes of a sealed class simply because Kotlin doesn't support zero-member data classes :/ – Oliver Charlesworth Dec 12 '17 at 10:43
  • @OliverCharlesworth Thank you for pointing that out. I presume I would then have to check whether all members are defined as 'val' as well. – Steven Jeuris Dec 12 '17 at 11:18
  • @OliverCharlesworth The second point you make (no zero-member data classes possible) is not a concern to me, as my abstract class includes an interface which needs to be implemented (not shown in the reduced code sample), thus every deriving member is guaranteed to have members. – Steven Jeuris Dec 12 '17 at 11:22
  • Apparently my previously posted code was incorrect (exactly because of the zero-member issue), so I have now included the abstract member in the abstract class. – Steven Jeuris Dec 12 '17 at 11:28

1 Answers1

0

Using reflection, the Kotlin class description (KClass) can be obtained using the ::class syntax on the instance you want to investigate (in your case, this::class in the initializer block of the abstract class). This gives you access to isData:

true if this class is a data class.

However, as Oliver points out, data classes can still contain var members, so you likely also want to check whether all member variables (and their member variables recursively) are defined as val to ensure immutability of all deriving classes.

Steven Jeuris
  • 18,274
  • 9
  • 70
  • 161