What’s the idea behind `error(message: Any)` accep...
# stdlib
m
What’s the idea behind
error(message: Any)
accepting type
Any
? Doesn’t this open up the potential bug of accidentally passing a
Throwable
which we would normally expect to do
throw IllegalStateException(cause: Throwable)
?
p
the advantage of
error
accepting any type to lazily format into an exception message is probably more significant than the disadvantage of passing an exception type directly in. also, cunningham’s law: there’s no way in the current type system to disallow one specific subtype but allow the rest
k
How is this lazy, and what are the advantages? Can you show me some usage example where this "laziness" is advantageous?
m
Yes, it seems to me that in the vast majority of cases you will be passing a
String
and, when you don’t, you simply use
.toString()
. Less uncertainty regarding what is working under the hood.
e
println()
takes
Any?
, so it actually seems like
error
does more work than necessary by requiring non-
null
in theory you could actually disallow
Throwable
by adding an forbidden overload, e.g.
Copy code
@Deprecated(level = DeprecationLevel.ERROR)
fun error(messsage: Throwable): Nothing = error(message as Any)

fun error(message: Any): Nothing = throw IllegalStateException(message.toString())
👍 1
I'm not sure that lazy formatting is really a good reason since
error
is unconditional. that would make more sense for e.g.
checkNotNull
, but that takes a lambda which makes it more obvious that the formatting is happening conditionally
1