We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
We define a function, f, which takes one integer argument, n, and returns Unit which is sort of like void in Java (because we don't need to return anything in particular, as the purpose of the function is to print the output "Hello World", not return it).
The function works by calling the to method of the Int class (1 to n) which creates a Range. Range has a method forEach, which applies a function to each element in the range.
The function applied to each element of the Range 1..n is this part of the code: _ => println("Hello World"). The Range class calls this function over and over again, each time passing in one of the values from 1 to n (so: 1, then 2, then 3, etc), but because we don't need to know which element we are currently on just to print Hello World, we ignore that argument, which is why we name it underscore (_).
Hello World N Times
You are viewing a single comment's thread. Return to all comments →
In the code above:
We define a function,
f
, which takes one integer argument,n
, and returnsUnit
which is sort of likevoid
in Java (because we don't need to return anything in particular, as the purpose of the function is to print the output "Hello World", not return it).The function works by calling the
to
method of theInt
class(1 to n)
which creates aRange
. Range has a methodforEach
, which applies a function to each element in the range.The function applied to each element of the Range 1..n is this part of the code:
_ => println("Hello World")
. The Range class calls this function over and over again, each time passing in one of the values from 1 to n (so: 1, then 2, then 3, etc), but because we don't need to know which element we are currently on just to printHello World
, we ignore that argument, which is why we name it underscore (_
).