In Kotlin, how do you declare a data class with zero constructor parameters? -
say want declare simple algebraic datatype integer lists:
sealed class intlist data class cons(val head: int, val tail: intlist): intlist() data class nil() : intlist() however, last declaration results in error
data class must have @ least 1 primary constructor parameter
- why limitation present? looking @ documentation, there seems no technical reasons requiring data class constructors non-nullary.
is possible express nullary constructors without having write lots of boilerplate code? if change last declaration like
sealed class nil() : intlist()then lose free implementations of
hashcode(),equals()come freedata classdeclarations.
edit
alex filatov gave nice short solution below. obviously, never need more 1 instance of nil, can define singleton object
object nil : intlist() however, if our lists parameterized type parameter? is, first 2 lines of our definition be
sealed class list<a> data class cons<a>(val head: a, val tail: list<a>): list<a>() we cannot declare polymorphic singleton nil object derives list<a> a, since have provide concrete type a @ time of declaration. solution (taken this post) declare a covariant type parameter , declare nil subtype of list<nothing> follows:
sealed class list<out a> data class cons<a>(val head: a, val tail: list<a>): list<a>() object nil : list<nothing>() this allows write
val xs: list<int> = cons(1, cons(2, nil)) val ys: list<char> = cons('a', cons('b', nil))
because data class without data doesn't make sense. use object singletons:
object nil : intlist()
Comments
Post a Comment