Does Kotlin DSL offer a way to require a pattern f...
# getting-started
m
Does Kotlin DSL offer a way to require a pattern for strings to follow? Either by regex or some validator function?
I'm looking for something similar to the "pattern" type from Json Schema: https://json-schema.org/understanding-json-schema/reference/regular_expressions.html
Looks like it's been requested here: https://youtrack.jetbrains.com/issue/KTIJ-17941
e
That would be an IDE-only feature anyway and you'd still have to check at runtime
Kotlin doesn't have structural subtypes or anything else that would allow you to declare a type that is a subset of
String
at compile time
you could push the requirement up with a (value) wrapper, for example
Copy code
class Patterned(val value: String) : CharSequence by value {
    init {
        require(regex.matches(value))
    }
}
would ensure that if you receive a
Patterned
value, it has passed the regex check. but it's not a
String
m
@ephemient thanks! So seems like there's nothing existing that can be used for static pattern checking while editing? I guess a custom plugin would have to be the way to go then
e
there are language injections supported by IntelliJ but I don't think there's anything existing for regex matches
r
If you just limit yourself to IntelliJ you could create custom inspections via structural thingie afaik those can be shared via VCS but never tried that
m
@Roukanken yeah I was looking at language injections to see how to define a custom one, but I can't find much documentation around it. I see https://plugins.jetbrains.com/docs/intellij/custom-language-support.html but that seems like overkill just for regex matching. https://plugins.jetbrains.com/docs/intellij/psi-cookbook.html too but that would require an existing built-in for regex it seems
r
uh, typescript because I had it open, but a regex match-y inspection is something you can whip real fast
I would have to play with it more, because rn I think it only detects one per class and not all of them, and only if they have exact one property to that object, but it's basically just an application of structural search/replace (and then saved as inspection):
(a function argument would be much simpler to find/define ofc)
m
@Roukanken 😮 I'm not familiar with that feature. Is that something that runs automatically to give you that warning or did you have to run it manually? Is there documentation for how to define a pattern?
r
There is a tiny bit of documentation here https://www.jetbrains.com/help/idea/structural-search-and-replace.html And it's a feature that's by default a (very intelligent) search, but you can save it to be run automatically as inspection (and set it to warning/error/...)
anyways I haven't played with it much, because info about it is pretty hard to find, but it sounds like task for this, if you have time to figure out how exactly 😄
m
Thanks, I'll be looking into this 🙂