is there any way to extend this so log() could tak...
# getting-started
j
is there any way to extend this so log() could take more than 1 parameter
g
You mean more than 1 parameter type? You could declare x as Any and then use a when block to merge the behaviours af the 3 different functions. However, if logging capabilities is what you're after, maybe you don't need to do that at all - just declare x: Any and call the toString() method
j
the problem is i want custom behavior for each type i've defined
g
in that case
Copy code
fun log(x: Any) = when(x) {
is Int -> ...
is String -> ...
}
👍 3
j
i'd prefer a way that doesn't use Any - i like the type safety of only being able to log values that i know i can handle
g
You can achieve that by using multiple functions, that's exactly what overloading is for. You can have type safety or brevity, but not both. If kotlin supported union types, you could theoretically use those, but frankly I personaly would kind of frown on that. I believe a function should either accept a specific value type, or it should accept any value and understand how to deal with the "else" case. In my view, logging is of the second variant. Why can't you can't have your cusotm logic for each type (Int, String, ...) in a when expression and then x.toString() in the else case?
j
the reason i want a union is because i'd like the type system to inform me when i need to add more cases to my logging rather than find out during run time
g
If you used overloaded functions, the type system would alert you to the fact that you are calling a non-existing function if you passed it an argument for which it wasn't defined, you don't need unions for that. Unions are really only useful when you want to return different types of values. In the when statement, you always have to have an "else" branch which would catch your case, so you also wouldn't find out at run-time, barring the situation where you intended to implement custom logic for a specific type but just forgot to do it. In certain situations you could possibly use a when statement and sealed classes (https://kotlinlang.org/docs/reference/sealed-classes.html). Or create a "Logable" interface with a custom log function and have all the classes you need implement it. There really are a lot of options and without more info about your use case, I can't give you a better recommendation.