is there a way to impl a custom interface for an f...
# getting-started
k
is there a way to impl a custom interface for an final class say "String"?
j
You mean make the existing
String
class implement your custom interface? This is not possible at the moment
k
OK. I just want to pass String to a fun that accept a custom Interface as param
s
Value classes will get you close, but it's not exactly what you want
j
Then maybe you can wrap that string into a custom class (possibly value class as Sam mentioned) that implements that interface. What does the interface look like?
k
The interface now just look like a placeholder
interface Selectable
the way @Joffrey I just noticed. It is a way to go. But It maybe annoying than just a String
j
I don't quite understand your point. If you're defining the parameter type to be this interface (and not string), isn't it the whole point to forbid other types like
String
?
k
Main idea is I want accept
Selectable
interface as param. Assume Class
Column
impl
Selectable
, so I can pass Column to the fun. Like SQL
SELECT Selectable
. so I want to let
String
Impl
Selectable
for some more common way to select.
j
For those cases you could probably create your own value class to wrap a string. It could even use an
init
block to perform validation on the string, because surely not any arbitrary string should be considered a
Selectable
, right?
k
Yes. @Joffrey you're right. I will try value class. and do more validation. correct is more important than simple.
🙏 1
Thanks
j
It will still be pretty simple to call, btw:
yourFunction(Sql("SELECT Selectable"))
(if we define
value class Sql(val text: String) : Selectable
)
k
I would have thought
Selectable
is anything that can be a parameter to
SELECT
- such as a column name or, indeed, any String literal. After all, both
SELECT mycolumn FROM mytable
and
SELECT 'any arbitrary string'
are both valid statements.
🙌 1
j
My bad, when King River Lee said "Like SQL `SELECT Selectable`" I didn't think twice and just took the whole thing at face value. But you're right, most likely only the part after
SELECT
is the string that is passed to the function. Nevertheless, I still believe it's worth using a type-safe column/selectable type for this, and maybe a simple string wrapper for a column name:
yourFunction(ColumnName("Selectable"))
👍 1
k
@Klitos Kyriacou is my main idea. that any thing impl
Selectable
can be param of
myFun(selectable: Selectable)