I have some code that builds up SQL expressions. I created a group of sealed classes.
sealed class SqlExpr
class SqlPiece(val sql: String) : SqlExpr()
class SqlAnd(vararg parts: SqlExpr) : SqlExpr()
...
It would be nice to write something like:
SqlAnd("x", someExpr, "foo is null", otherExpr)
instead of:
SqlAnd(SqlPiece("x"), someExpr, SqlPiece("foo is null"), otherExpr)
In some languages I could declare that Strings
are SqlExprs
. In others I could declare an implicit conversion from String
to SqlPiece
. Any recommended style for this situation in Kotlin?
In Java, you’d probably create an overload with Object...
vararg type and convert the instances appropriately. You don’t even need to throw an exception for anything that isn’t String
or SqlExpr
, you could just call toString
on everything that isn’t an SqlExpr
and wrap that resulting String (which would also allow you to pass String-like classes like StringBuilder).
I’d guess in Kotlin you can do the same with varargs parts: Any
.
I may just use that. While not as perfectly type-safe, in practice it’s useful.
I also forgot, an extension property or method on String
is another option…
SqlAnd("x".toSql(), someExpr, ...)
SqlAnd("x".sql, someExpr, ...)