fun Int.isBuzz() : Boolean { return this % 5 == 0; } fun main(args : Array<String>) { for (i in 1..100) { println( when (#(i % 3, i.isBuzz())) { #(0, true) -> "FizzBuzz"; #(0 ,false) -> "Fizz"; #(1 ,true), #(2 ,true) -> "Buzz"; else -> i; }); } }
The type of specialness that tuples have in are threefold. Syntax, language integration, and generics.
First, Kotlin gives Tuples a special language syntax of their own. A Hash followed by a parenthesized list of stuff constitutes a tuple. This is a shorthand notation for a tuple. Tuples are usually significant in their order, but if you prefix the value with a label then that value gets a name and it can be accesses by that name. It becomes a very lightweight way to define data structures that are only needed locally.
Second, there is a good deal of language integration with tuples. The void equivalent return type
Unit
is actually a Tuple0
as well, which is a tuple with zero members. And Kotlin uses the tuple mechanism to allow a function to return multiple types. Even though the JVM and JavaScript VMs only allow a single return type, Kotlin does an end run by making the return a tuple. While you could do this yourself with Object arrays and one off classes Kotlin integrates this practice so you can take only your favorite parts of the return in your code rather than swallowing the whole horse pill.Finally, there is a good amount of generics integration with the tuple. Since each position can be a different type Kotlin integrates the type of the position into the type signature of the particular tuple you are using. This is more important when you consider that Kotlin generics are fully reifiable.
Of course, I haven't come up with a good way to demonstrate reifiable generics in a FizzBuzz solution. And until someone does we should not expect the typical developer to get it right.
No comments:
Post a Comment