Tour of Scala

ネストしたメソッド

Language
Info: JavaScript is currently disabled, code tabs will still work, but preferences will not be remembered.

Scalaではメソッドの定義をネストする(訳注:入れ子にする)ことができます。 以下のコードは与えられた数値の階乗を計算するためのfactorialメソッドを提供します。

 def factorial(x: Int): Int = {
 def fact(x: Int, accumulator: Int): Int = {
 if (x <= 1) accumulator
 else fact(x - 1, x * accumulator)
 } 
 fact(x, 1)
 }
 println("Factorial of 2: " + factorial(2))
 println("Factorial of 3: " + factorial(3))

このプログラムの出力は以下の通りです。

Factorial of 2: 2
Factorial of 3: 6

Contributors to this page:

Contents

AltStyle によって変換されたページ (->オリジナル) /