4 ms·
You can do that sort of thing in Kotlin, which is an OOP (well, multi-paradigm) language: inline fun <reified T> String.fromString(): T { return wh
by repolfx 7y ago
You can do that sort of thing in Kotlin, which is an OOP (well, multi-paradigm) language:
inline fun <reified T> String.fromString(): T {
return when {
T::class == String::class -> this
T::class == Int::class -> Integer.valueOf(this)
else -> TODO()
} as T
}
val str: String = "abc".decode()
val int: Int = "123".decode()
You have to be careful with type inference: if there's no way for the compiler to figure out what type you want from the call site, you'll get an error.
You might say this isn't OOP in the strictest possible sense, but extension methods + type inference + reified types gives what you're asking for in a way that's natural for an OOP programmer.
- chriswarbo 7y ago> You have to be careful with type inference: if there's no way for the compiler to figure out what type you want from the call site, you'll get an error. I'd say that's a feature, not a bug :) > You might say this isn't OOP in the strictest possible sense I would say it's not OOP in any sense. Having one function implement all the different behaviours, and pick which one to run by switching on some data (in this case the class tag) is a classic example of being not OOP. As a bonus, this ignores dynamic dispatch (the only implementation is for `String`) and it's not polymorphic (the same code doesn't work for different types; instead we have different clauses for each type). This would be salvagable if `String::fromString` only enforced the type constraint, and dispatched to `T::fromString` to do the actual parsing, e.g. inline fun <reified T> String.fromString(): T { return when { T::class == String::class -> this else -> T::fromString(this) } as T } I'm not sure whether that would work or not (I've never written Kotlin), but I still think it's "messy" (monkey-patching methods on to classes, reimplementing dynamic dispatch manually, inspecting classes (via the equality check), going out of our way to prevent infinite loops, etc.)
- repolfx 7y agoYou can do that via reflection and other tactics, yes. You'd better do it with an interface and a cast, as of course "fromString" may not exist. I also wouldn't use this pattern but, it is possible, and Kotlin is an OOP language.