Compile-time calculation: Difference between revisions
m
→{{header|Wren}}: Changed to Wren S/H
m (Added more explanation about Java's compile time limitations.) |
m (→{{header|Wren}}: Changed to Wren S/H) |
||
(3 intermediate revisions by 2 users not shown) | |||
Line 838:
=={{header|Java}}==
<pre>
The Java compiler is able to calculate expressions that contain constant variables
and certain operators during code compilation.
Line 843 ⟶ 844:
As defined in the Java language specification,
the following operators and expressions may be used for constant expressions:
Unary operators: +, -, ~, !
Multiplicative operators: *, /, %
Line 854 ⟶ 856:
Parenthesized expressions whose contained expression is a constant expression
Simple names that refer to constant variables
</pre>
<syntaxhighlight lang="java">
Line 1,456 ⟶ 1,459:
=={{header|Scala}}==
Scala 3 supports proper compile time evaluation
<syntaxhighlight lang="scala">
transparent inline def factorial(inline n: Int): Int =
inline n match
case 0 => 1
case _ => n * factorial(n - 1)
inline val factorial10/*: 3628800*/ = factorial(10)
</syntaxhighlight>
Alternative version that works with Scala 2:
<syntaxhighlight lang="scala">object Main extends {
val tenFactorial = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2
Line 1,714 ⟶ 1,731:
Not that it makes much difference in practice as the compiler which is written in C is so quick (at least with scripts of moderate length and on modern hardware) that the compile and runtime stages are indistinguishable to the user.
<syntaxhighlight lang="
System.print(factorial10)</syntaxhighlight>
|