3 ms·
Say you'd like to have a foo method that returns... a number, whatever. You do not need to have multiple symbols "fooString", "fooDecimal", "fooString", etc. S
by ohgodplsno 6y ago
Say you'd like to have a foo method that returns... a number, whatever.
You do not need to have multiple symbols "fooString", "fooDecimal", "fooString", etc. Simply overloading the parameters gives you type safety, and keeps a single foo symbol.
fun foo(value: String): Int = value.length()
fun foo(value: Int) = value
fun foo(value: RemoteDatabase) = value.servers.map { it.connect().executeSql("SELECT 1")[0].toInt() }.sum()
All these define a foo method, that returns an Int. The untyped alternative (what javascript, python, etc do in a naive way, without trying to duck type) is to do this:
fun foo(value: Any) = when (value) {
is Int -> value
is String -> value.length()
is RemoteDatabase -> value.servers.map { ... }.sum()
else -> error("Welp, our type system couldn't help us there.")
}
Additionally, if it really makes sense, you can define foo as an extension function on the type:
fun Int.foo() = this
fun String.foo() = length()
fun RemoteDatabase.foo() = servers.map { ... }.sum()
You can then use it directly on the type, rather than call foo(1):
val fooResult = 1.foo()
val fooStringResult = "Well hello there".foo()