Conditional Implicit Functions in Scala

I am trying to create a DSL in Scala. For this, I would like to create an implicit function for exact 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 change this to create this implicit function only for certain strings. Can a logical condition be possible for an implicit function, so that an implicit function is created only when the logical condition is true (for example, if the string length is 5 or more, if the first letter of the string is the letter "a", etc.), but not for all lines?

+5
source share
1 answer

Short answer

No, It is Immpossible.

Types and implications are allowed at compile time, while the actual value of your String is a runtime object, that is, it can be different between runs. Therefore, at compile time, it is impossible to know which string value will be passed to the implicit function.

Long answer

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

Here is the idea: you can create your own type for your string and encode the necessary conditions in this type. For example, you will have AString[String[...]] for a string starting with "a", String[String[String[StringNil]]] for a 3 letter string, etc.

All string conversions will result in the corresponding types, for example, when you add String[...] with the letter A , you get AString[String[...]] , etc.

See dependent types and implementation of HList .

But then again, this is hardly practical in your case.

UPD Also consider the Refined project, which provides type-level predicates.

+6
source

Source: https://habr.com/ru/post/1247081/


All Articles