7.4. Procedury

W przypadku definiowania metod zwracających rezultat typu Unit można użyć specjalnej składni, która polega na pominięciu znaku równości oraz ujęciu wyrażenia definiującego ciało metody w nawiasy klamrowe. W pliku Procedures1.scala zdefiniowane są dwie metody — f1 i f2 — mające podobne działanie.

Plik Procedures1.scala:
def f1(x: Int) = println("x : " + x)
def f2(x: Int) { println("x : " + x) }

Definicja metody f2 wykorzystuje wspomnianą specjalną składnię. Poniższe przykłady ilustrują działanie obu metod.

scala> :load Procedures1.scala
Loading Procedures1.scala...
f1: (x: Int)Unit
f2: (x: Int)Unit

scala> f1(1)
x : 1

scala> f2(1)
x : 1

W przypadku użycia tej alternatywnej składni, nie jest dozwolone jawne wyspecyfikowanie typu zwracanego przez metodę. A zatem definicja metody z pliku Procedures2.scala jest niepoprawna.

Plik Procedures2.scala:
def f3(x: Int): Unit { println("x : " + x) }

Próba kompilacji tej metody kończy się błędem.

scala> :load Procedures2.scala
Loading Procedures2.scala...
<console>:1: error: illegal start of declaration (possible cause: missing `=' in front of current method body)
def f3(x: Int): Unit { println("x : " + x) }
                       ^
<console>:1: warning: Detected apparent refinement of Unit; are you missing an '=' sign?
def f3(x: Int): Unit { println("x : " + x) }
                     ^

Specyfikacja języka Scala opisuje definiowanie procedur w punkcie 4.6.4.

Język programowania Scala Wydanie 2. Copyright © Grzegorz Balcerek 2016

Licencja Creative Commons

Ten utwór jest dostępny na licencji Creative Commons Uznanie autorstwa-Na tych samych warunkach 4.0 Międzynarodowe.

Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.