2

I am new to Kotlin and am still trying to find my way around. I know from this question that val can be overriden with var in a class that inherits it, but is this true the other way around? If it isn't, is there any workaround that might be available?

Community
  • 1
  • 1
Anonymous Person
  • 307
  • 2
  • 10

1 Answers1

3

It is possible to override val with var because the later has more information than the former.

A var property encapsulates a get and a set, while a val contains only a get. That way var overrides the get of the val and add its set (because why not).

The other way around is obviously not true.

voddan
  • 31,956
  • 8
  • 77
  • 87
  • That's what I figured. Not to worry, I devised a workaround that works for my purposes anyways. Keep a boolean indicating if the var has already been set. In the set method, check the boolean. If it is false, then modify the var and set it to true. Otherwise, ignore it and don't set anything. Then, no further modifications can be made. – Anonymous Person Aug 06 '16 at 13:28
  • Hm, that does not look like the initial question, but anyway. Take a look at [delegated properties](https://kotlinlang.org/docs/reference/delegated-properties.html). What you need is very similar to `Delegates.notNull()` with a slight modification. – voddan Aug 06 '16 at 14:26
  • You may take an implementation of this from here: https://youtrack.jetbrains.com/issue/KT-7180. Don't forget to vote ;) – voddan Aug 06 '16 at 14:26
  • Thanks! For your help, I entrust you with one vote. :D – Anonymous Person Aug 06 '16 at 21:30
  • Vote not for me, but on the issue i gave you a link to. That will help to put it into stdlib – voddan Aug 07 '16 at 05:17