https://kotlinlang.org logo
Title
r

Ruckus

12/19/2018, 5:21 PM
You would need to define a custom
operator fun contains
object Links {
    <values here>

    operator fun contains(link: String) = when (link) {
        HELP, SHOP, BLOG, ... -> true
        else -> false
    }
}
👍 1
s

Shawn

12/19/2018, 5:24 PM
I’m having a hard time thinking of a convenient way of providing that logic though - you could maybe add all the constants to a hashset or something and update it every time you added or removed a constant but that’s kinda annoying, or use a big
when
but similar issue
r

Ruckus

12/19/2018, 5:25 PM
I added an example of a when, but yeah, there's no way without listing off the values.
j

Jake

12/19/2018, 5:25 PM
Thanks!
👍 1
s

Shawn

12/19/2018, 5:25 PM
I was considering maybe recommending using an enum and using
.values()
but that’s problematic for other reasons
r

Ruckus

12/19/2018, 5:26 PM
Indeed
k

kz

12/19/2018, 5:29 PM
How about something like this:
object Links {
    private val values = mutableSetOf<String>()
    private operator fun String.unaryPlus(): String = this.also { values += it }

    val HELP = +"https://..."
    val SHOP = +"https://..."
    val BLOG = +"https://..."
    val GALLERY = +"https://..."

    operator fun contains(string: String) = string in values
}
🤯 3
basically the public property also registers with a set which you can then easily test membership.
The unary
+
operator can be replaced with a more readable method invocation.
s

Shawn

12/19/2018, 5:30 PM
Nice! Maybe a hair overengineered but that’s pretty clever 👍
r

Ruckus

12/19/2018, 5:31 PM
That still requires remembering the
+
(or some other function call), and means you can't have the values be
const
.
j

Jake

12/19/2018, 5:31 PM
Lets say I have "help.123.com/help_me" as the only item in values and I check for "help.123.com" in values would that return false?
s

Shawn

12/19/2018, 5:32 PM
@Ruckus true, not a perfect solution - it’d suck to have a test fail because you accidentally forgot to add a
+
at the start of a constant
k

kz

12/19/2018, 5:33 PM
It would return false. For that logic you would need to augment the
contains
implementation. My snippet was just how you might handle the boilerplate. @Ruckus definitely some downsides to using the
+
. I was just going for something non-intrusive. The only alternative I can think of would require reflection or a lot more boilerplate (or enums as someone else mentioned)
s

Shawn

12/19/2018, 5:33 PM
@Jake yes, that
in
check would return false, it’s just a simple
equals
call
j

Jake

12/19/2018, 5:33 PM
Perfect. You guys rock.
r

Ruckus

12/19/2018, 5:35 PM
@kz Your solution was pretty slick, don't get me wrong. I don't mean to throw it out, just point out the trade-offs to make an informed decision.
k

kz

12/19/2018, 5:35 PM
🙂 I definitely agree.
👍 1
g

gsala

12/20/2018, 9:41 AM
@Jake you could declare the links in an enum instead of an object and then check with
Links.values().any { ... }