Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Implicit functions in Scala

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 ?

like image 550
Dust009 Avatar asked Apr 14 '16 00:04

Dust009


People also ask

What is implicit function in Scala?

Implicit parameters are the parameters that are passed to a function with implicit keyword in Scala, which means the values will be taken from the context in which they are called.

Is a function called by the Scala compiler when a type conversion is required?

1)Implicit Function: An implicit function called automatically when compiler thinks it's good to do so. It means that if your code doesn't compile but would if a call made to an implicit function, scala will call that function to make it compile.


1 Answers

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.

like image 97
Aivean Avatar answered Sep 30 '22 09:09

Aivean