Conditional Implicit functions in Scala
Asked Answered
D

1

5

I'm trying to design a DSL in Scala. For that, I'd like to create an implicit function on precise strings. I know that to create an implicit function for any String, I could write:

class StringPlus(str: String) {
    def some_function(): Unit = do_something
}
implicit def string2StringPlus(str: String) = new StringPlus(str)

But I do not know how to modify this to create this implicit function only for certain strings. Could it be possible to give a boolean condition to the implicit function so that the implicit function is created only when the boolean condition is true (for instance, if the string has a length of 5 or more, if the first letter of the string is the letter "a", etc.) and not for all the strings ?

Dumbwaiter answered 14/4, 2016 at 0:0 Comment(2)
Are your strings constants at compile time (e. g. magicMethod "this-is-always-foo") or are they run-time dependent (e. g. magicMethod readFromStdIO)?Dicarlo
Can you say how you would use this implicit function? I can't see how it can usefully be used, even if it were possibleGrahamgrahame
L
7

Short answer

No, it's not possible.

Types and implicits are resolved at compile time, while the actual value of your String is runtime entity, i.e. it may be different between runs. So it's not possible at compile time to know which string value is going to be passed to implicit function.

Long answer

It may be possible, but includes enormous amount of type magic and it's definitely is not a good solution in terms of readability and practicality.

Here is the idea: you can create custom type for your string and encode necessary conditions in that type. For example, you'll have AString[String[...]] for the string that starts with "a", String[String[String[StringNil]]] for the 3-letter String, and so on.

All string transformations will then result appropriate types, like, when you're prepending String[...] with letter A, you'll get AString[String[...]], and so on.

Take a look at dependent types and the implementation of HList.

But again, it's hardly practical in your case.

UPD: Also take a look at Refined project, that provides type-level predicates.

Lonnylonslesaunier answered 14/4, 2016 at 0:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.