Given:
class Appropriate {}
class Inappropriate {
fun toImmutable() : Appropriate
}
val foo: MutableList<whatever>
val baz: Inappropriate
desire1 is compile time errors:
fun bar(vararg how: ???) { /*...*/ }
bar(foo) // compile time error: MutableList foo cannot be used as a parameter of bar
bar(1, foo) // compile time error: MutableList foo cannot be used as a parameter of bar
bar(1, "", baz, foo, foo) // compile time error: Inappropriate baz cannot be used as a parameter of bar
bar(baz.toImmutable()) // yes
bar(foo.toList()) // yes
bar(1, foo.toList()) // yes
bar(1, "", foo.toList(), foo.toList(), foo.toList()) // yes
Desire2 is magic that doesn’t involve the developer and could be paired to the error checking:
fun bar(vararg how: Any) { /*...*/ }
bar(foo) // yes, bar magically does NOT receive foo but foo.toList()
bar(1, foo) // yes, bar magically does NOT receive foo but foo.toList()
bar(1, "", baz, foo, foo) // yes, bar magically does NOT receive baz but baz.toImmutable()
bar(foo.toList()) // yes
bar(baz.toImmutable()) // yes
bar(1, foo.toList()) // yes
bar(1, "", foo.toList(), foo.toList(), foo.toList()) // yes
Desire 3 is runtime errors:
fun bar(vararg how: Any) { /*...*/ }
bar(foo) // throws IllegalArgumentException: MutableList foo cannot be used as a parameter of bar, use toList
bar(1, foo) // throws IllegalArgumentException: MutableList foo cannot be used as a parameter of bar, use toList
bar(1, foo, foo, foo) // throws IllegalArgumentException: MutableList foo cannot be used as a
parameter of bar, use toList
bar(1, "", baz, foo, foo) // throws IllegalArgumentException: Inappropriate baz cannot be used as a parameter of bar
bar(foo.toList()) // yes
bar(baz.toImmutable()) // yes
bar(1, foo.toList()) // yes
bar(1, "", foo.toList(), foo.toList(), foo.toList()) // yes
I wanted to learn if kotlin has something better than to loop the varargs and validate their type one by one inside the function, or to have the discipline and memory to call toList or whatever safety conversion without fail