https://kotlinlang.org logo
#getting-started
Title
# getting-started
k

King River Lee

11/03/2023, 2:36 PM
is there a way to impl a custom interface for an final class say "String"?
j

Joffrey

11/03/2023, 2:37 PM
You mean make the existing
String
class implement your custom interface? This is not possible at the moment
k

King River Lee

11/03/2023, 2:38 PM
OK. I just want to pass String to a fun that accept a custom Interface as param
s

Sam

11/03/2023, 2:38 PM
Value classes will get you close, but it's not exactly what you want
j

Joffrey

11/03/2023, 2:38 PM
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

King River Lee

11/03/2023, 2:38 PM
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

Joffrey

11/03/2023, 2:44 PM
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

King River Lee

11/03/2023, 2:48 PM
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

Joffrey

11/03/2023, 2:50 PM
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

King River Lee

11/03/2023, 2:52 PM
Yes. @Joffrey you're right. I will try value class. and do more validation. correct is more important than simple.
🙏 1
Thanks
j

Joffrey

11/03/2023, 2:52 PM
It will still be pretty simple to call, btw:
yourFunction(Sql("SELECT Selectable"))
(if we define
value class Sql(val text: String) : Selectable
)
k

Klitos Kyriacou

11/03/2023, 3:34 PM
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

Joffrey

11/03/2023, 3:37 PM
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

King River Lee

11/05/2023, 10:42 AM
@Klitos Kyriacou is my main idea. that any thing impl
Selectable
can be param of
myFun(selectable: Selectable)
2 Views