6

How can I declare a property with a custom setter, but without getter in Kotlin? In Anko for example they do it like this:

var myProperty: Type
    @Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) 
    get() = AnkoInternals.noGetter()
    set(value) { field = value; /* setter logic */ }

But it looks a bit hacky to me. Is this a right way to do so? If yes, then what about the case when a project doesn't have Anko dependency?

P.S. Let me be clear - I want to have no getter at all, rather than private getter

Community
  • 1
  • 1
arslancharyev31
  • 1,801
  • 3
  • 21
  • 39
  • I thought objects were immutable in Kotlin. I'm new to the language, so I'm not sure. It's a more functional style, is it not? No, I'm wrong: https://kotlinlang.org/docs/reference/properties.html – duffymo Jul 25 '17 at 19:19
  • 2
    Possible duplicate of [Private getter and public setter for a Kotlin property](https://stackoverflow.com/questions/38243085/private-getter-and-public-setter-for-a-kotlin-property) – zsmb13 Jul 25 '17 at 19:20
  • @zsmb13, nope, I don't intend to have a private getter, but rather no getter at all – arslancharyev31 Jul 25 '17 at 19:21
  • 1
    Still the same question, you're looking for a write-only property. Deprecating the setter is still the best way to go for this use case. – zsmb13 Jul 25 '17 at 19:22
  • @duffymo, I'm new as well, but I'm not sure whether properties are a feature of functional programming – arslancharyev31 Jul 25 '17 at 19:22
  • Functional programming means functions and immutable objects. That's the beauty of it: Everything is inherently thread safe and parallelizable. – duffymo Jul 25 '17 at 19:24
  • Kotlin allows programming in procedural, object-oriented, and functional styles, you can mix them without any restrictions. – Miha_x64 Jul 26 '17 at 07:50

2 Answers2

8

Deprecating the getter is still the only way to get the effect.

You don't need an Anko dependency, just use the @Deprecated annotation with an appropriate level.

Tom
  • 4,910
  • 5
  • 33
  • 48
voddan
  • 31,956
  • 8
  • 77
  • 87
1

voddan's answer was great, but I can also supplement it with how I implemented it:

@get:Deprecated(message = "no.", level = DeprecationLevel.ERROR)
lateinit var property: Any

here I use the lateinit modifier and the @Deprecated annotation for the getter.

d1snin
  • 101
  • 1
  • 11