File: manual.xml

package info (click to toggle)
nice 0.9.12-2
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 7,220 kB
  • ctags: 6,894
  • sloc: java: 42,767; xml: 3,508; lisp: 1,079; sh: 736; makefile: 673; cpp: 21; awk: 3
file content (2245 lines) | stat: -rw-r--r-- 79,509 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
<?xml version="1.0" standalone="no"?>
<!DOCTYPE book PUBLIC '-//OASIS//DTD DocBook XML V4.1.2//EN'
'http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd' [
<!ENTITY nice "Nice">
<!ENTITY java "Java">
<!ENTITY NULL "<literal>null</literal>">
<!ENTITY LT "<literal>&lt;</literal>">
<!ENTITY GT "<literal>&gt;</literal>">
<!ENTITY LBRACE "<literal>{</literal>">
<!ENTITY RBRACE "<literal>}</literal>">
]>

<book>
  <bookinfo>
    <title>The Nice user's manual</title>
    <author><firstname>Daniel</firstname><surname>Bonniot</surname></author>
    <author><firstname>Bryn</firstname><surname>Keller</surname></author>
    <author><firstname>Francis</firstname><surname>Barber</surname></author>
    <copyright><year>2003</year><holder>Daniel Bonniot</holder></copyright>
  </bookinfo>
  <preface><title>Foreword</title>
    <para>
      This manual describes the Nice programming language.
      It is currently under redaction, which means that many aspects of 
      the language are absent from it, or that some sections are mostly empty.
      During this time, it is recommended to read also the 
      <ulink url="http://nice.sf.net/language.html">Nice tutorial</ulink>, 
      which contains lots of additional information.
      Both documents currently assume some knowledge of Java, or at least
      of an object oriented language.
    </para>

    <para>
      The authors of this manual are Bryn Keller and Daniel Bonniot, with
      contributions from Francis Barber.
    </para>
  </preface>

  <chapter><title>Philosophy</title>
    <para>
      <blockquote>
	<attribution>Alan J. Perlis</attribution>
	<para>
	  A language that doesn't affect the way you think about programming, 
	  is not worth knowing.
	</para>
      </blockquote>

      <blockquote>
	<attribution>Alfred North Whitehead</attribution>
	<para>
	  The art of progress is to preserve order amid change 
	  and to preserve change amid order.
	</para>
      </blockquote>

      The Nice programming language is a new object-oriented programming 
      language based on Java. 
      It incorporates features from functional programming, 
      and puts into practice state-of-the-art results from academic research. 
      This results in more expressivity, modularity and safety.
    </para>

    <variablelist>
      <varlistentry><term>Safety</term>
	<listitem>
	  <para>
	    Nice detects more errors during compilation than existing 
	    object-oriented languages (null pointer accesses, 
	    cast exceptions).
	    This means that programs written in Nice never throw the infamous
	    <literal>NullPointerException</literal> nor 
	    <literal>ClassCastException</literal>.
	    This aspect is developed in more detail in 
	    <ulink url="http://nice.sf.net/safety.html">this article</ulink>.
	  </para>
	</listitem>
      </varlistentry>

      <varlistentry><term>Modularity</term><listitem><para>
	    In object-oriented languages, it is possible to add a new class 
	    to an existing class hierarchy. 
	    In Nice, it is also possible to add <emphasis>methods</emphasis> to 
	    existing classes without modifying their source file. 
	    This is a special case of <emphasis>multi-methods</emphasis>.
	  </para>
	</listitem>
      </varlistentry>

      <varlistentry><term>Expressivity</term><listitem><para>
	    Many repetitive programming tasks can be
	    avoided by using Nice's advanced features. 
	    Ever got bored
	    of writing tons of loops, casts, overloaded methods with default
	    values, ... ?
	  </para>
	</listitem>
      </varlistentry>
    </variablelist>

  </chapter>

  <chapter id = "packages" ><title>Packages</title>
    <para>
     A <firstterm>package</firstterm> is a group of related classes, 
     methods, and variables. You can declare that all the code in a particular
     <literal>.nice</literal> file belongs to a certain package with the 
     declaration:
    </para>
    <para>
      <literal>package <replaceable>package-name</replaceable>;</literal>
    </para>
    <para>
     To make use of all the public entities from another Nice package,
     use the <literal>import</literal> statement:
    </para>
    <para>
      <literal>import <replaceable>package-name</replaceable>;</literal>
    </para>
    <para>
      Note that this is somewhat different from Java packages.
      In Java, a class can be used independently of its declaring package.
      In Nice methods can be declared outside classes, so importing
      the whole package is important to know the methods available for a
      given class.
      This probably implies that Nice projects should be designed with
      smaller, self-contained packages that Java projects.
    </para>
    <para>
      Therefore, only whole packages can be imported.
      It is not possible to import a single class.
      Likewise, there is no need to 
      include a <literal>.*</literal> after the package name as in Java. 
      In fact, using <literal>.*</literal> indicates that you wish to import 
      the contents of a Java package rather than a Nice package. 
      See the section on <link linkend="importJava">Java imports</link> 
      for details.
    </para>
    <section id="mainMethod"><title>The <literal>main</literal> method</title>
      <para>
        If a package contains a method whose name is <literal>main</literal>
	and the method has a <literal>void</literal> return type and takes
	a single <literal>String[]</literal> as its argument, this method
	receives special treatment, in that when the program is run, execution
	will begin with this <literal>main</literal> method. The runtime
	system will pass the command line arguments used to invoke the program
	as the argument to <literal>main</literal>.
      </para>
      <para>
        Note that since the main unit of code in Nice is the package, 
	and not the class, the <literal>main</literal> method should
	be implemented outside of any class declaration.
      </para>
    </section>
  </chapter>

  <chapter><title>Classes and Interfaces</title>
    <section><title>Declaring a class</title>
      <para>
      </para>
    </section>

    <section><title>Fields</title>
      <para>
	The main component of a class is the list of its fields.
	A field is a variable that is attached to each instance of
	the class. It has a type, a name, and optionally a default 
	initial value.
	The syntax for field declaration is:
	<programlisting>
	  <type><replaceable>type</replaceable></type> <replaceable>field-name</replaceable><optional> = <replaceable>initial-value</replaceable></optional>;
	</programlisting>
	If no default value is given, then every call to the constructor
	must specify the value for this field.
	If it is given, a call to the constructor call still override
	it with a different value, in which case the default value is
	not computed (this fact is only important if it has side effects).
      </para>
    </section>

    <section id="constructor"><title>Constructors</title>
      <para>
	Classes in Nice have a default (or "automatic") constructor 
	which is generated
	automatically by the compiler. This constructor allows all the
	fields of the class to be specified explicitly, though if the
	field has a default value in the class definition, it can be
	omitted from the constructor call and the default value will
	be used. In many cases this default constructor is all that
	is needed, and it saves the programmer from having to write
	tedious code that simply accepts values and assigns them to
	fields.
      </para>

      <example><title>Class definition and creations using the automatic constructor</title>
	<programlisting lang="nice">
class Car
{
  String brand;
  String model;
  int numberOfWheels = 4;
  int numberOfDrivingWheels = 2;
}

void test()
{
  Car renault5 = new Car(brand: "Renault", model: "Cinq");
  Car jeep = new Car(brand: "Jeep", model: "Some jeep", numberOfDrivingWheels: 4);
}</programlisting>
      </example>
      
      <para>
	It is required to include the names of the fields in the call
	to the constructor. 
	This is important for two reasons.
	First, it is easy to understand what the arguments represent, without looking at the
	class definition.
	Second, it does not require some arbitrary ordering of the fields
	<footnote>
	  <para>
	    A problem happens in Java when the order of the parameters 
	    of a constructor should be changed.
	    This requires modifying all the call sites, which is at best tedious
	    and error-prone, at worse impossible (when writing a library used by others).
	    When the order is changed and some caller are not modified,
	    the following happens:
	    if the exchanged parameters have incompatible types, 
	    the compilation of the caller will fail; 
	    otherwise the code might even compile and produce
	    wrong results at runtime. 
	    There is no simple way to solve this issue in Java.
	    Using names in the call to the constructor in Nice is the solution.
	  </para>
	</footnote>. Because the names of the fields are used, they can be given
	in any order.
      </para>

      <para>
        When more control over construction is desired, it is possible
	to write new constructors that can be used in place of the
	automatic constructor. These are written much like any other
	method, but they use a slightly different declaration syntax:
	<programlisting>
	  new <type><replaceable>class-name</replaceable></type>(<type><replaceable>param-type</replaceable></type><replaceable>param-name</replaceable><optional> = <replaceable>initial-value</replaceable></optional>, ...) 
	  { 
	    <replaceable>method-body</replaceable>;
	    this(<replaceable>argument</replaceable>, ...);
	  }
	</programlisting>
	This syntax requires that the last statement in any custom 
	constructor calls some other constructor for the same type.
	In most cases, the automatic constructor will be called.
      </para>
      <example><title>Class definition and creations using custom constructors</title>
	<programlisting lang="nice"><![CDATA[
/** 
 * Class which encapsulates a strategy for 
 * way of translating a character.
 */
class Translator
{
  //The function that actually performs the translation
  char->char transFunction;

  //convenience method 
  char translate(char input) 
    {
      return (this.transFunction)(input);
    }
}

/**
 * Constructor which takes a map of characters, and
 * returns a Translator which looks up the input 
 * character in the map, or just returns the input
 * character if it's not in the map.
 */
new Translator(Map<char,char> characters) 
{
  this(transFunction: char c => characters.get(c) || c);
}




//A translator which provides rot13 ciphering.
//Uses automatic constructor.
var Translator rot13 = new Translator(transFunction: 
				      char c => char(int(c) + 13));

//A translator which just changes 's' or 'S' to '$'.
//Uses custom constructor.
var Translator sToDollar = new Translator(characters: listToMap([
						      ('s', '$'), 
						      ('S', '$')
						      ]));
	]]></programlisting>
      </example>
      <para>
      It is also possible to define <firstterm>initializers</firstterm>
      for your classes. An initializer is simply a block of code that
      executes after construction is finished. To define an initializer,
      simply include code directly in the class definition, inside
      a block:
	<programlisting>
	  class <type><replaceable>class-name</replaceable></type>
	  { 
	    {
	      <replaceable>initializer</replaceable>
	    }
	    <replaceable>fields-and-methods</replaceable>
	  }
	</programlisting>
      </para>
      <para>
        Here is an example. Notice that since the initializer runs
	after any constructors, the hidden counter field will always
	be set to zero, even if the caller had tried to set it to
	some other value when the object was created.
      <example><title>Class initializers</title>
	<programlisting lang="nice"><![CDATA[
class Counter
{

    { 
      this._internal_counter = 0;
    }

  int _internal_counter = 0;
}

	]]></programlisting>
      </example>

      </para>
    </section>

    <section id = "parametricClasses" ><title>Parametric classes</title>
      <para>
        A powerful feature of Nice is the ability to define 
        <firstterm>parametric classes</firstterm>.
        Parametric classes are like templates in C++, or similar constructs in
        various functional languages. Programming with parametric classes is
        sometimes called <firstterm>generic programming</firstterm>.
      </para>      
      <para>
        A parametric (or parameterized) class is simply a class which has a 
        parameter. In this case the parameter is a <emphasis>type</emphasis>
        rather than a value. You can consider a parametric class as a family
        of related classes, all of which have the same behavior and structure
        except for the part that is parameterized. A common case where this
        is useful is in data structures.
      </para>
  <example><title>Simple Java Collection</title>
	<programlisting lang="java">
class Stack
{
  List contents = new LinkedList();
  void push(Object o) 
  {
    contents.add(o);
  }
  
  //... omitted methods

  public static void main(String[] args)
  {
    Stack st = new Stack();
    st.push("Test");
    Integer num = (Integer)st.pop(); // Runtime error
  }
}
</programlisting>
      </example>
      <para>
        There is a big type safety problem here.
        We pushed a String on to the stack, and then tried to pop it off into
        an Integer, resulting in an exception at runtime. Parametric classes
        can solve this problem.
      </para>
  <example><title>Simple Nice Collection</title>
	<programlisting lang="nice"><![CDATA[
class Stack<T>
{
  List<T> contents = new LinkedList();
  void push(T t) 
  {
    contents.add(t);
  }
  
  //... omitted methods

}

void main(String[] args)
{
  Stack<String> st = new Stack();
  st.push("Test");
  Integer num = st.pop(); // Compile time error!
}
]]></programlisting>
      </example>
      <para>
        In the Nice version, we have parameterized <classname>Stack</classname> by 
        a type <type>T</type>. Essentially, <type>Stack&lt;T&gt;</type> 
        is a recipe for the compiler that tells it how to create a 
	<classname>Stack</classname> that 
        works for any given type. So now the compiler knows that we only mean 
        for Strings to go into our stack, and it reports an error when we
        write code that expects an <type>Integer</type> to come out of our 
        <type>Stack&lt;String&gt;</type>. 
      </para>
    </section>
    <section><title>Declaring an Interface</title>
     <para>
       Nice has single inheritance, like Java or C#, which means that each 
       class can have at most one superclass which it extends. Sometimes,
       it would be nice to have a class that "extends" two (or more) different 
       classes, taking some of its behavior and data from each. 
       In Nice, as in Java, this can be accomplished via 
     <firstterm>interfaces</firstterm>.
     </para>
     <para>
       Interfaces are declared just like classes, except that they may
       not contain data fields, only methods. Unlike in Java, they may
       also contain default implementations of the methods, making 
       interfaces more convenient and useful than Java interfaces.
     </para>
     <para>
       To say even this much is still to think of interfaces in Java terms,
       however. In Nice, an interface
       doesn't really "contain" anything at all, it's just a marker.
       Just as <literal>java.io.Serializable</literal> is just a tag
       to tell Java that it's okay to use serialization on instances of
       a class, all Nice interfaces are really tags.
     </para>
     <para>
       This is because Nice 
       has multi-methods, which are defined by themselves and not contained
       in a class or interface. It is always possible to define new 
       methods for an interface, just as it is always possible to define
       new methods for a class. Another consequence of the fact Nice is
       based on multi-methods is that interface definitions can "contain"
       not only method signatures, but also default implementations.
     </para>
     <para>
       Nice does accept a style of interface definition similar to Java's,
       as in the following example:
      <example>
        <title>Declaring an Interface</title>
        <programlisting lang="nice">
interface Component
{

  String getID();

  (int,int) getPosition();

  (int,int) getDimensions();

  int getArea() 
  {
    (int width, int height) = this.getDimensions();
    return width * height;
  }

}
        </programlisting>
      </example>      
     </para>
     <para>
       However, it's equally possible to define the same interface
       in this style:
      <example>
        <title>Declaring an Interface with External Methods</title>
        <programlisting lang="nice">
interface Component {}

String getID(Component comp);

(int,int) getPosition(Component comp);

(int,int) getDimensions(Component comp);

int getArea(Component comp) 
{
  (int width, int height) = comp.getDimensions();
  return width * height;
}
        </programlisting>
      </example>      
      and in fact, it's fine to mix the two styles, declaring 
      some of the methods inside the <literal>interface</literal>
      block, and some outside. One good practice might be to
      declare those methods which have no default implementation
      inside the <literal>interface</literal> block, and those
      with default implementations outside of it. That way someone
      reading the code will have a clear idea of which methods
      must be implemented when implementing an interface. Of
      course, the compiler will ensure that all necessary methods
      are implemented, so this is only a suggestion.
     </para>
    </section>
    <section id="enums"><title>Enumerations</title>
      <para>
      Enumerations or simply (<literal>enum</literal>s) are a group
      of related constants. Many languages support defining simple
      constants, and of course <link linkend="constants">Nice does 
      also</link>. Many programs are written to use certain numeric
      constants with special meanings. For instance, one might
      write a method for a vending machine:
      <programlisting lang="nice">
	let int NICKEL = 5;
	let int DIME = 10;
	let int QUARTER = 25;

	class VendingMachine
	{
	  int change = 0;
	}
	
        void addCoin(VendingMachine machine, int cents)
	{
	  machine.change += cents;
	}
      </programlisting>
      but this method isn't very safe! It will accept any amount of
      change, including nonsensical amounts like 3, or 234320. One
      way to address this problem would be to do runtime checks to
      ensure that the value is acceptable, and throw an exception if
      it is not. However, there is an easier solution in Nice: the enum.
	<programlisting>
	  enum <type><replaceable>class-name</replaceable></type><optional>(<type><replaceable>parameter-type</replaceable></type> <replaceable>parameter-name</replaceable>, ...)</optional>
	  { 
	    <replaceable>option,...</replaceable>
	  }
	</programlisting>
      Enums can be simple symbols like
      <programlisting lang="nice">
      enum Color { Red, Orange, Yellow, Blue, Indigo, Violet }
      </programlisting> 
      or they can contain integer (or other) values:
      <programlisting lang="nice">
        enum VendingCoin(int value) 
	{
	  nickel(5), dime(10), quarter(25);
	}
	
	class VendingMachine
	{
	  int change = 0;
	}
	
        void addCoin(VendingMachine machine, VendingCoin cents)
	{
	  machine.change += cents.value;
	}
      </programlisting>
      Of course, a realistic vending machine would have to keep track of 
      the actual number of each coin rather than a total value!
      </para>
           
      
    </section>
  </chapter>


  <chapter id="method"><title>Methods</title>
    <section><title>Declaring methods</title>
      <para>
        Method declaration takes the following form:
      </para>

      <para>
        <literal>
        <optional><replaceable>type-parameters</replaceable></optional> 
        <replaceable>return-type</replaceable> 
        <replaceable>method-name</replaceable>
        (<optional><replaceable>parameters</replaceable></optional>);
        </literal>
      </para>

      <para>
	Note that in Nice, methods can be defined within the
        body of a class definition, or outside of it - both are identical
        for the compiler's purposes.
      </para>

      <para>
        It is also possible to define a default implementation at the same
        time that the method signature is defined. This form looks like:
      </para>
      <para>
        <literal>
        <optional><replaceable>type-parameters</replaceable></optional> 
        <replaceable>return-type</replaceable> 
        <replaceable>method-name</replaceable>
        (<optional><replaceable>parameters</replaceable></optional>)
        {
	  <replaceable>code-body</replaceable>
        }
        </literal>
      </para>
    </section>
    <section><title>Implementing methods</title>
      <para>
        In comparison to their declarations, method implementations can be
        quite terse:
      </para>

      <para>
        <literal>
	<replaceable>method-name</replaceable>
        (<optional><replaceable>arguments</replaceable></optional>)
	&LBRACE; body &RBRACE;
        </literal>
      </para>

      <para>There is also a special form for methods which consist of a single expression:</para>

      <para>
        <literal>
	<replaceable>method-name</replaceable>
        (<optional><replaceable>arguments</replaceable></optional>)
	= <replaceable>expression</replaceable>;
        </literal>
      </para>

      <para>
        The <optional><replaceable>arguments</replaceable></optional>
	consist of names, and optionally types, of the form
      </para>

      <para>
        <literal><replaceable>name</replaceable></literal>
      </para>

      <para>or</para>

      <para>
        <literal><replaceable>class-name</replaceable> <replaceable>name</replaceable></literal>
      </para>

      <para>
        The <literal><replaceable>class-name</replaceable></literal> 
	is used to specialize the method on that argument. 
	An example should make the difference clear. Also note the
        use of both the block- and expression-style methods.
      </para>

      <example>
        <title>Method Implementation</title>
        <programlisting lang="nice">
class Vehicle {}
class Motorcycle extends Vehicle {}
class Car extends Vehicle {}

//Declare method
int numberOfWheels(Vehicle vehicle);

//Default implementation
numberOfWheels(vehicle) 
{
    throw new Exception("Unknown number of wheels!");
}

//Specialize for Cars
numberOfWheels(Car car)
{ 
    return 4;
}

//Specialize for Motorcycles
numberOfWheels(Motorcycle mc) = 2;

        </programlisting>
      </example>

      <para id="exactMatching">
       It is also possible to specialize a method on the 
       <emphasis>exact</emphasis> class of the argument. Then the method will
       apply to arguments which match the class exactly, and 
       <emphasis>not</emphasis> to an argument which is a subclass of the class
       specified. The syntax for exact matching is:
      </para>
      <para>
       <literal>#<replaceable>class-name</replaceable> <replaceable>name</replaceable></literal>
      </para>

      <para>
        Specializing on the exact class of an argument is useful in situations
	where an implementation is correct for a certain class, but you know
	that each subclass will require a different implementation.	
      </para>

      <para>
        There is also an <link linkend="ex:copy">example</link> where 
	exact matching is required to
	type-check a method with a precise polymorphic type.
      </para>

      <para>     
       When specializing a method with type parameters, it is not necessary 
       or possible to restate the type parameters in the method implementation.
       However, if you need access to the type parameters as in the example
       below, use the syntax:
      </para>
      <para>
        <literal>
	&LT;<replaceable>type-parameters</replaceable>&GT;
	<replaceable>method-name</replaceable>
        (<optional><replaceable>arguments</replaceable></optional>)
	&LBRACE; body &RBRACE;
        </literal>
      </para>
      <example>
       <title>Using Type Parameters in Method Implementations</title>
       <programlisting lang="nice"><![CDATA[

//Method definition
<T> T lastItem(Collection<T> coll);


/* This version is incorrect because the type parameter T is not in scope:

lastItem(coll)
{
  Iterator<T> it = coll.iterator();
  //...
}
*/

// This one will work correctly:
<T> lastItem(coll)
{
  Iterator<T> = coll.iterator();
  //...
}
]]></programlisting>
      </example>
        <para>
         Note that it is not possible to dispatch a method call on an array 
         type, nor to specialize a method on the subtype of a type parameter. 
         This means that method implementations of the form:
        </para>
        <para>
         <literal><![CDATA[foo(Collection<String> string){}]]></literal>
        </para>
        <para>or</para>
        <para>
         <literal><![CDATA[foo(String[] array){}]]></literal>
        </para>
        <para>
         are not valid. You should use respectively the specializers
	 <literal>Collection</literal> and 
	 <literal>Array</literal> instead.
        </para>        
       
    </section>
    <section><title>Value Dispatch</title>
      <para>
            In addition to choosing a method based on the classes of the
            arguments, it's even possible to override a method based on the
            actual values of the arguments. Currently this feature works 
            with integers, booleans, strings, characters, enums, and 
	    class instances which are used as package level constants. 
	    It is also possible to override a method for the special case
	    of null.
      </para>
      <para>
	    This feature makes it
            convenient to code things that might otherwise have required
            switch statements or nested if/else statements. Using value 
            dispatch can be more flexible than switch or if/else statements,
            because you can always add new alternatives conveniently by
            just adding a new method implementation.
      </para>
	<example>
	<title>Value Dispatch</title>
	<programlisting lang="nice"><![CDATA[
String digitToString(int digit, String language)
  requires 0 <= digit < 10;

digitToString(digit, language)
{
  throw new Exception("Couldn't convert "digit" to language "language);
}

digitToString(1, "english") = "one";
digitToString(2, "english") = "two";
digitToString(3, "english") = "three";

digitToString(1, "french") = "un";
digitToString(2, "french") = "deux";
digitToString(3, "french") = "trois";

String booleanToYesNo(boolean bool);

booleanToYesNo(true) = "yes";
booleanToYesNo(false) = "no";

enum Grade {
  A, B, C, D, F
}

Grade charToGrade(char input);

charToGrade('a') = A;
charToGrade('b') = B;
charToGrade('c') = C;
charToGrade('d') = D;
charToGrade('f') = F;
charToGrade(input) {
  throw new IllegalArgumentException("Not a grade letter: " + input);
}

char gradeToChar(Grade grade);
gradeToChar(A) = 'a';
gradeToChar(B) = 'b';
gradeToChar(C) = 'c';
gradeToChar(D) = 'd';
gradeToChar(F) = 'f';

class Person
{
}

let Person BOB = new Person();

void greet(Person p)
{
  println("Hello, anonymous person!");
}

greet(BOB)
{
  println("Hi Bob!");
}

<T> int containsHowMany(?List<T> list);

<T> containsHowMany(List list) = list.size();
containsHowMany(null) = 0;

]]></programlisting>
      </example>

    </section>
    <section id="namedParameters"><title>Named parameters</title>
      <para>
	When <link linkend="call">calling</link> a method
	it is possible to specify the name of a parameter, followed by
	<literal>:</literal> before the value given to that parameter.
	Named parameters can be given in any order.
	This is useful when writing the call, because one does not
	need to remember the order of the arguments, but only their names.
	This makes the code much easier to understand
	what each parameter represents, provided that parameter names are
	chosen carefully.
	
	<example>
	  <title>Using named parameters</title>
	  <programlisting lang="nice">
void copy(File from, File to) { ... }
...
copy(from: f1, to: f2);
copy(to: f3, from: f4);</programlisting>
	</example>
	
	It is of course still possible to omit the names of the parameters,
	in which case the arguments must be given in the order of the 
	declaration.
      </para>
    </section>

    <section id="optionalParameters"><title>Optional parameters</title>
      <para>
	Many methods have some parameters that are used most of the time
	with the same value. In Nice, a parameter can be given a default
	value. That argument can then be omitted when calling the method, 
	and the	default value will be used. 

	<example>
	  <title>Using named and optional parameters</title>
	  <programlisting lang="nice">
void copy(File from, File to, int bufferSize = 1000) { ... }
...
copy(from: f1, to: f2); // with a buffer size of 1000
copy(from: f1, to: f2, bufferSize: 4000);</programlisting>
	</example>

	In the method definition, the optional parameters should be 
	listed after the required parameters. This is needed to allow 
	calls that do not name the arguments and want to use the default
	values for the optional parameters.
      </para>
      <para>
       Note that the optional values of parameters can be based on other
       parameters, for example:
      </para>
      <para>
       <literal> T[] slice(T[] array, int from = 0, 
       int to = array.length - 1);</literal>
      </para>

      <para>
        Method implementations must still bind all parameters,
	including the optional ones, and can dispatch on them.
      </para>

    </section>
  </chapter>

  <chapter id="contracts"><title>Assertions and contracts</title>
    <section><title>Syntax</title>
      <para>
        The syntax for assertions is the same as in Java (since 1.4).
        Assertions are statements of the following form:
	<literal>assert &lt;boolean expression&gt; : &lt;error message&gt;</literal>.
        The &lt;error message&gt; is optional.
      </para>
      <para>
        Preconditions are introduced with the <literal>requires</literal>
	keyword, and postconditions with the <literal>ensures</literal>
	keyword. If there are several conditions in either section,
	they must be separated by commas. 
	For convenience, an optional trailing comma is accepted.
      </para>
      <para>
        In a method returning a value, the special variable name
	<literal>result</literal> can be used to refer to the result value
	of the method in the postcondition. 
	The <literal>old</literal> to refer to values before the 
	execution of the method is not supported yet.
      </para>
      <para>
	For example, we can define the contract of the add method
	of a <type>Buffer</type> interface.
	It is guaranteed that <literal>isEmpty</literal> returns 
	<literal>true</literal>	if, and only if, 
	<literal>size</literal> returns <literal>0</literal>.
	The <literal>add</literal> method can be called only when the buffer
	is not full. It is guaranteed to make the buffer non-empty, and
	to increase the size by one.

	<example>
	<title>Contracts</title>
	<programlisting lang="nice"><![CDATA[
interface Buffer<Elem>
{
  int size();

  boolean isFull();
  boolean isEmpty() ensures result == (size() == 0);

  void add(Elem element)
    requires
         !isfull() : "buffer must not be not full"  // A comma here is optional
    ensures
         !isEmpty() : "buffer must not be empty",   // Note the comma
         size() == old(size()) + 1 : "count inc";
}]]></programlisting>
      </example>
      
      </para>
    </section>

    <section id="enablingAssertions"><title>Enabling assertions and contract checking</title>
      <para>
        By default, assertions and contracts are not used at runtime.
	They are discarded by the just-in-time compiler, and should
	cause no slow-down.
	They can be turned on when starting the JVM.
      </para>

      <section><title>JDK 1.4 and later</title>
        <para>
	  The mechanism is the same as for Java assertions. 
	  Checking can be enabled at runtime with 
	  <userinput>java -ea ...</userinput>.
	</para>
      </section>

      <section><title>JDK 1.1, 1.2 and 1.3</title>
        <para>
          Contrarily to Java, Nice produces programs with assertions that can 
	  be run on earlier JDKs. Therefore there is no problem to distribute 
	  Nice programs using assertions and contracts. Since java will not 
	  know the <literal>-ea</literal> command line option, they are 
	  disabled by default. You can enable them with 
	  <userinput>java -Dassertions=true ...</userinput>.
	</para>
      </section>
    </section>

  </chapter>

  <chapter><title>Statements</title>
    <section id="localVars"><title>Local variables and constants</title>
     <para>
       Local variables may be defined with the <literal>var</literal> keyword.
       Here is the syntax:
     </para>
     <para>
      <literal>var <optional><replaceable>type</replaceable></optional> 
      <replaceable>variable-name</replaceable> 
      <optional>= <replaceable>initial-value</replaceable></optional>
      ;
      </literal>
     </para>
     <para>
       For local variables (not <link linkend = "packageVars">package 
       variables</link>), the Nice also accepts the Java style of 
       declaration:
     </para> 
     <para>
      <literal>
      <replaceable>type</replaceable> 
      <replaceable>variable-name</replaceable> 
      <optional>= <replaceable>initial-value</replaceable></optional>
      ;
      </literal>
     </para>
     <para id="constants">
      Constants are declared with "let":
     </para>
     <para>
      <literal>let <optional><replaceable>type</replaceable></optional> 
      <replaceable>variable-name</replaceable> 
      <optional>= <replaceable>initial-value</replaceable></optional>
      ;
      </literal>
     </para>
     <para id="monomorphicLet">
       If the variable or constant is of a simple type (i.e., not a 
       <link linkend="parametricClasses">parameterized type</link>), then it is
       not necessary to specify the type yourself, the compiler can infer
       the correct type automatically.
     </para>
    </section>
    <section id="packageVars"><title>Package variables and constants</title>
     <para>
      Since Nice uses <link linkend="packages">packages</link> as its largest
      conceptual unit, variable and constant declarations may appear 
      outside class definitions, and are useful in the same way that 
      static variables in Java are. Package variables are introduced
      with <literal>var</literal>, and package constants with
      <literal>let</literal>. The type must be specified, since it is
      a useful documentation.
     </para>
    </section>
    <section id="forStatements"><title>Extended <literal>for</literal> statement</title>
     <para>
      Nice supports the traditional <literal>for</literal> loop, with the same
      syntax as in Java. In addition, it provides a form that allows iterating 
      over the items in a sequence like C#'s <literal>foreach</literal>.
      Here is the syntax:
     </para>
     <para>
      <literal>for (
      <replaceable>item-type</replaceable> 
      <replaceable>variable-name</replaceable> : 
      <replaceable>container</replaceable> ) { <replaceable>body</replaceable> }
      </literal>
     </para>
     <para>
      Currently, this version of the <literal>for</literal> statement can be
      used to iterate over <literal>Collection</literal>s, arrays, 
      <literal>Range</literal>s,
      <literal>String</literal>s, and <literal>StringBuffer</literal>s.
     </para>
     <para>
      <example><title>Extended <literal>for</literal> statement</title>
	<programlisting lang="nice">
let String[] strings = ["one", "two", "three"];
for(String s : strings)
{
  println(s);
}
</programlisting>
      </example>
     </para>
     <para>
     Since Nice also has syntax for generating ranges of numbers, 
     another convenient way to use the <literal>for</literal> statement
     is as follows:
      <example><title>Extended <literal>for</literal> with Ranges</title>
	<programlisting lang="nice">
//Print numbers from 1 to 10, inclusive
for(int i : 1..10)
{
  println(i);
}
</programlisting>
      </example>
     </para>
    </section>
    <section id="localMethods"><title>Local methods</title>
      <para>
	Local methods are similar to regular methods (defined
	at the package or class level), 
        except that they are defined inside another method,
        and therefore only usable in that scope.
	They can refer to local variables from their context.
	Like <link linkend = "anonymousMethods">anonymous methods</link>,
	local methods cannot be overridden.
      </para>

      <example><title>Local method</title>
	<programlisting lang="nice">
Window createMyWindow()
{
  Window w = new Window();
  
  void addMyButton(String text)
  {
    w.addButton(new Button(text));
  }

  addMyButton("One");
  addMyButton("Two");
  addMyButton("Three");
}</programlisting>
      </example>

    </section>

  </chapter>

  <chapter><title>Expressions</title>
    <section id="call"><title>Method calls</title>
      <para>
        A call is usually of the form <literal>f(e1, ..., en)</literal>.
	<literal>f</literal> can be a method name, or
	more generally any expression which has a method type
	(for instance, a local parameter).
	<literal>e1, ..., en</literal> is the list of arguments to the 
	method. Arguments can optionally be 
	<link linkend="namedParameters">named</link>.
      </para>

      <para>
        In many object-oriented languages, methods are called with the
	syntax <literal>e1.f(e2, ..., en)</literal>. This syntax is also 
	accepted in Nice, and is completely equivalent to the previous one.
	In particular, <literal>e.f</literal> can be used to retrieve the value
	of the field <literal>f</literal> in the object <literal>e</literal>
	<footnote>
	  <para>
	    A consequence of these rules is that if the field 
	    <literal>f</literal> contains a method, it must be called with
	    <literal>(e.f)(e1, ..., en)</literal>.
	  </para>
	</footnote>.
      </para>

      <para>
        It is possible that a name refers to several unrelated methods.
	In that case, the types (and if applicable names)
	of the arguments are used to try to disambiguate which method
	must be called. If only one method is applicable, it is called.
	Moreover, if several methods are applicable, but one has a more
	restricted domain than all the others, it is chosen
	<footnote>
	  <para>
	    For instance, suppose two methods
	    <literal><![CDATA[<T> void foo(Collection<T>)]]></literal> and 
	    <literal><![CDATA[<T> void foo(List<T>)]]></literal> are declared, 
	    and <literal>aList</literal> is an expression of static type 
	    <type>List</type>.
	    The expression <literal>foo(aList)</literal> will result in
	    calling the second <literal>foo</literal> method, 
	    because <type>List</type>
	    is a subclass of <type>Collection</type>.
	  </para>
	</footnote>.
	Otherwise, the compiler reports an ambiguity error.
      </para>
        <section id="blockCall"><title>Block Syntax for Method Calls</title>
	  <para>
	    Nice supports an alternative syntax for method calls when one 
	    of the arguments is a method of type <literal><type>void-&gt; 
	    <replaceable>T</replaceable></type></literal>:
	  </para>
	  <programlisting lang="nice">
	    <replaceable>method-name</replaceable>(<replaceable>argument</replaceable>, ...)
	    {
	      <replaceable>argument-body</replaceable>
	    }
          </programlisting>
	  <para>
	    If an <link linkend = "anonymousMethods">
	    anonymous method</link> would normally be used, it is permissible
	    to omit the arguments and <literal>=></literal> and instead write
	    the code for the anonymous method in a block following the call. 
	    An example will be helpful:
	  </para>
	  <example id="blockSyntaxEx">
	  <title>Block syntax for method calls</title>
	  <programlisting lang="nice"><![CDATA[
	  //First define the method we're going to call:
	  //Like an 'if' statement
	  void when(boolean condition, void->void action)
	  {
	    if (condition)
	      action();
	  }	    

	  //Now exercise our method with block syntax:
	  void main(String[] args) 
	  {
	    when(1 > 0) 
	    {
	      println("Math is working correctly!");
	    }
	  }
	  ]]></programlisting> 	  
	  </example>
	  <para>
	  Note that we could just as easily have written:
	  <programlisting>
	    when(1 > 0, () => { 
	      println("Math is working correctly!");
	    });
	  </programlisting>
	  but with the alternative block call syntax, the code becomes
	  less cluttered, and easier to read. It also helps to eliminate
	  the distinctions between built-in statements and user-defined
	  methods. For instance, the standard <literal>using</literal> 
	  statement is actually just a method defined in the standard 
	  library.
	  </para>
	</section>
    </section>

    <section><title>Tuples</title>
      <para>
       A tuple is a grouping of several values in a single expression.
       For instance, <literal>("Hello", 2*3, x.toString())</literal> 
       is a tuple whose elements are the string <literal>"Hello"</literal>,
       the number <literal>6</literal> and the string representation of 
       <literal>x</literal>. 
       The type of a tuple is a <emphasis>tuple type</emphasis>, 
       whose elements are the types of the corresponding values.
       The type of our example tuple is 
       <literal>(String, int, String)</literal>. 
      </para>

      <para>
       A tuple can be of any length. In english, a tuple of two elements
       is called a couple. For an arbitrary number n, a tuple of n
       elements is called a n-tuple.
      </para>

      <para>
       Tuple types are covariant, so a couple of <type>int</type>s 
       can be used where a couple of <type>long</type>s is expected.
      </para>

      <para>
       A funny feature is that swapping two variables can be done without a 
       temporary variable, using tuples: <literal>(x, y) = (y, x)</literal>.
       An important use of tuples is to allow a method
       to return several values. <xref linkend="tupleEx" /> defines
       and uses the method <literal>minMax</literal>, which takes 
       two integers, and returns the smallest first, the biggest second.
      </para>

      <example id="tupleEx">
	<title>Method returning several values using a tuple</title>
	<programlisting lang="nice"><![CDATA[
(int, int) minMax(int x, int y) = x < y ? (x, y) : (y, x);

void printTuple((int x, int y))
{
  println("(" + x + ", " + y + ")");
}

void main(String[] args)
{
  printTuple(minMax(14, 17));
  printTuple(minMax(42, 41));
}
]]></programlisting>

	<para>
	 Note that <literal>printTuple</literal> has only one argument,
	 which is a tuple. We give the names <literal>x</literal> and
	 <literal>y</literal> to the two components of this tuple, so that
	 we can use them directly in the implementation of the method.
	</para>
      </example>

    </section>

    <section><title>Arrays</title>
      <para>
      An array can be created by simply enclosing the elements of the
      new array in brackets. 
      </para>
      <para>
            <literal><replaceable>class-name</replaceable>[]
	    <replaceable>variable-name</replaceable> = [
	    <replaceable>element1</replaceable>,
	          <replaceable>element2</replaceable>, ...]</literal>
      </para>
      <para>
      It is also possible to create an array
      which is filled with nulls, or some single value, or a value
      which is calculated on a cell-by-cell basis, by using the 
      <literal>fill</literal> method in the standard library.
      <example>
      <title>Initializing an array with a single value</title>
      <programlisting lang="nice"><![CDATA[
      //Fill every cell with the value 5000.
      int[] points = new int[10];
      fill(points, 5000);
      ]]></programlisting>
      </example>
      <example>
      <title>Initializing an array with a calculated value</title>
      <programlisting lang="nice"><![CDATA[     
      //build a little table of squares 
      int[] squares = fill(new int[10], int i => i * i);
      ]]></programlisting>
      </example>
      </para>
    </section>

    <section><title>String Literals</title>
      <para>
      Literal strings are surrounded with double quotes, for instance:
      </para>
      <para>
      <literal>
      String s = "Hello";
      </literal>
      </para>
      <para>
      The backslash character <literal>\</literal> is used for escaping,
      as in Java.
      </para>
      <section id="multiLine"><title>Multi-line Strings</title>
        <para>
          Nice also allows multi-line string literals, using syntax borrowed
          from the Python language. Multi-line strings begin and end with 
          three double quotes. Within multi-line strings, double quotes do
          not need to be escaped, unless there are three in a row. 
        </para>
        <example>
        <title>Multi-line strings</title>
        <programlisting lang="nice"><![CDATA[
        let greeting  = """
            Hello, world.
	    You may be thinking, "Why was I called here today?"
	    Well, there was a good reason. Honest.
        """;      
        ]]></programlisting>
        </example>
      </section>
      <section id="stringConcat"><title>String concatenation</title>
        <para>
	  Just as in many other languages, strings can be concatenated
	  using the plus (<literal>+</literal>) operator.
	</para>
        <para>
          Strings can also be combined by simple juxtaposition - that is, by
          placing them side by side with some other expression. For
          example:
        </para>
        <example>
          <title>String concatenation</title>
          <programlisting lang="nice"><![CDATA[
        String name = "Nice";
        int factor = 10;
        println("My favorite language is " name ", which is " factor 
                   " times better than what they make me use at work.");
        ]]>
          </programlisting>
        </example>
      </section>
    </section>

    <section id="anonymousMethods"><title>Anonymous methods</title>
      <para>
       Since Nice allows methods to be passed as arguments, and
       returned as results, it is convenient to allow small anonymous methods
       to be defined at the same point in the program in which they are used,
       similar to the use of anonymous classes in Java. Anonymous methods 
       cannot be overridden, and have exactly one implementation.
      </para>
      <para>
       The syntax of anonymous methods is:
      </para>
      <para>
        <literal>
        (<optional><replaceable>parameters</replaceable></optional>)
        => &LBRACE; body &RBRACE;
        </literal>
      </para>
      <para>
       As with named methods, there is also a single-expression format:
      </para>
      <para>
        <literal>
	(<optional><replaceable>parameters</replaceable></optional>)
	=> <replaceable>expression</replaceable>
        </literal>
      </para>
      <para>
       The parentheses around the parameters are optional if there is only one
       parameter.
      </para>
      <para>
       The return type of an anonymous method is automatically determined by 
       the compiler using a process called 
       <firstterm>type inference</firstterm>, so it is not necessary or possible
       to specify it.
      </para>
<example>
<title>Using Anonymous Methods</title>
<programlisting lang="nice"><![CDATA[
String concat(Collection<String> strings) 
{
    StringBuffer buff = new StringBuffer();
    strings.foreach(String s =>  {
        buff.append(s);
    });
    return buff.toString()
}

var String[] numberStrings = [1,2,3,4,5].map(int num => String.valueOf(num));

//Another way of defining "concat"
String concat2(Collection<String> strings)
{
  return strings.foldLeft((String accum, String s) => accum + s, "");
}
]]></programlisting>
</example>
    </section>

    <section id="operators"><title>Operators</title>
      <para>
        Nice supports a wide range of operators which will be familiar to 
        most programmers. The table below lists the operators, ordered from 
	highest precedence to lowest precedence.
      </para>
      <table><title>Operators</title>
        <tgroup cols='3'>

	<thead>
	  <row>
	    <entry>Operator</entry>
	    <entry>Kind</entry>
	    <entry>Associativity</entry>
	  </row>
	</thead>

        <tbody>

 <!-- Lifted from http://nice.sourceforge.net/cgi-bin/twiki/view/Doc/NiceExpressions -->
<row><entry>  <literal> () </literal>  </entry><entry>   grouping  </entry><entry>  none  </entry></row>
<row><entry>  <literal> [], . </literal>  </entry><entry>  postfix  </entry><entry>  left  </entry></row>

<row><entry>  <literal> new </literal>  </entry><entry>  prefix  </entry><entry>  right </entry></row>
<row><entry>  <literal> ++, -- </literal>  </entry><entry>  postfix  </entry><entry>  left  </entry></row>

<row><entry>  <literal> +, -, ++, --, ~, ! </literal>  </entry><entry>  prefix  </entry><entry>  right  </entry></row>
<row><entry>  <literal> ** </literal>  </entry><entry>  binary  </entry><entry>  right  </entry></row>

<row><entry>  <literal> *, /, % </literal>  </entry><entry>  binary  </entry><entry>  left  </entry></row>
<row><entry>  <literal> +, - </literal>  </entry><entry>  binary  </entry><entry>  left  </entry></row>

<row><entry>  <literal> &lt;&lt;, &gt;&gt;, &gt;&gt;&gt; </literal>  </entry><entry>  binary  </entry><entry>  left  </entry></row>
<row><entry>  <literal> .. </literal>  </entry><entry>  binary  </entry><entry>  left  </entry></row>

<row><entry>  <literal>  &lt;, &lt;=, &gt;, &gt;= </literal>  </entry><entry>  binary  </entry><entry>  both  </entry></row>
<row><entry>  <literal> instanceof </literal>  </entry><entry>  binary  </entry><entry>  left  </entry></row>

<row><entry>  <literal> =, ! </literal>  </entry><entry>  binary  </entry><entry>  left  </entry></row>
<row><entry>  <literal> &amp; </literal>  </entry><entry>  binary  </entry><entry>  left  </entry></row>

<row><entry>  <literal> ^ </literal>  </entry><entry>  binary  </entry><entry>  left  </entry></row>
<row><entry>  <literal> | </literal>  </entry><entry>  binary  </entry><entry>  left  </entry></row>
<row><entry>  <literal> &amp;&amp; </literal>  </entry><entry>  binary  </entry><entry>  left  </entry></row>

<row><entry>  <literal> || </literal>  </entry><entry>  binary  </entry><entry>  left  </entry></row>
<row><entry>  <literal> ?: </literal>  </entry><entry>  ternary  </entry><entry>  right  </entry></row>

<row><entry>  <literal> =&gt; </literal>  </entry><entry>  binary  </entry><entry>  right  </entry></row>
<row><entry>  <literal> *=, /=, %=, +=, -=, &amp;=, ^=, _=, &lt;&lt;=, &gt;&gt;=, &gt;&gt;&gt;=, = </literal>  </entry><entry>  binary  </entry><entry>  right  </entry></row>
        </tbody>
	</tgroup>
      </table>
    </section>

    <section id="conversion"><title>Conversion between primitive types</title>
      <para>
	The numeric primitive types are, from the largest to the smallest:
	<type>double, float, long, int, short, byte</type>.
	Conversion from a smaller to a larger type is automatic.
	Conversion from a larger to a smaller type must be done explicitly,
	since they can lose information about the magnitude of the value.
      </para>
      <para>
	The explicit conversion is done by calling a special method, 
	whose name is the target type. 
	If <replaceable>e</replaceable> is a numeric expression,
	and <replaceable>type</replaceable> one of the numeric types, then 
	<literal><replaceable>type</replaceable>(<replaceable>e</replaceable>)</literal> 
	will convert the value of the expression, so that it is
	represented as a value in <replaceable>type</replaceable>.
	This is equivalent to the 
	<literal>(<replaceable>type</replaceable>) e</literal>
	syntax in &java;.
      </para>
      <para>
      	In most cases, characters should be treated as abstract entities
	and not as the numbers that happen to encode them. Therefore,
	the <literal>char</literal> type is not a numeric type in Nice. 
	Operations on characters can be performed using the methods of class
	<literal>java.lang.Character</literal>.
        Additionally, it is possible to convert a character
	<literal>c</literal> to its integer value with 
	<literal>int(c)</literal>,
	and to convert an integer to the character it encodes with
	<literal>char(i)</literal>.
      </para>
      <para>
        For instance, here is code to read
	characters from a <type>Reader</type>, whose 
	<literal>read</literal> method returns an <type>int</type> 
	(<literal>-1</literal> meaning that the end of stream has been 
	reached):

	<example><title>Converting a value of a primitive type</title>
	<programlisting lang="nice">
let reader = new BufferedReader(new InputStreamReader(System.in));

int v;
while ((v = reader.read()) != -1) {
  char c = char(v);
  ... // Do something with the character.
}</programlisting>
      </example>

      </para>
    </section>
  </chapter>

  <chapter id="interfacingWithJava"><title>Interfacing with Java</title>
    <section><title>Using Java from Nice</title>
      <para>
        The Java libraries are automatically imported as necessary. 
	Therefore it is straightforward	to use existing Java code
	in Nice programs.
	In particular, it is possible to call Java methods, to
	instantiate Java classes, to create a Nice subclass of a Java
        class, overriding methods from the parent, ...
      </para>

      <para>
	This section lists advanced features related to the use of Java code
	in Nice.
      </para>

      <section id="subclassJavaInNice"><title>Subclassing a Java class</title>
	<para>
	  A Nice class can extend a Java class, simply by naming it in
	  its <literal>extends</literal> clause. Similarly, it can
	  implement Java interfaces.	
	</para>

	<para>
	  When instantiating a Nice class with a Java parent, the 
	  <link linkend="constructor">automatic constructor</link>
	  comes in several versions, one for each constructor of the
	  parent class. The call must then provide the values for one
	  of the constructors of the parent, followed by the named
	  values for the fields defined in the Nice class.
	</para>
      </section>

      <section id="importJava"><title>Importing packages</title>
	<para>
	  When Java classes of some package are used frequently,
	  it is possible to make the package part of their name implicit.
	  For instance, after a declaration
	  <literal>import java.io.*;</literal> it is possible
	  to refer to class <type>java.io.File</type>
	  with the short name <type>File</type>. It is not possible to 
          import only a single name, such as 
          <literal>import java.io.File;</literal>, you must import the whole
          package.
	</para>

	<para>
	  Classes defined in the current package always have priority
	  over imported packages. If a short name is used that refers
	  to two classes from imported packages, the compiler
	  will report an ambiguity, and the fully qualified name must be used.
	</para>
      </section>

      <section id="optionTypesJava"><title>Option types</title>
	<para>
	  Nice's advanced type system makes the distinction between normal 
	  (e.g. <type>String</type>) and option
	  (e.g. <type>?String</type>) types, which allows to 
	  prevent <literal>NullPointerExceptions</literal>
	  (see <link linkend="optionTypes">option types</link>).
	  This poses a problem when using 
	  existing Java libraries. If my Nice program calls a Java method
	  that returns a <type>String</type> (the Java type), 
	  does it mean <type>String</type> or 
	  <type>?String</type> in Nice? 
	  Since Java allows the value to be &NULL;, 
	  the Nice compiler 
	  currently supposes it's <type>?String</type> (it can only be 
	  sure about primitive types like <type>int</type>).
	</para>

	<programlisting lang="java">
// Java code
public class MyJavaClass {
  public String getName() {
    return "foo";
  }
}	</programlisting>

	<para>
          In Nice, if <literal>myJavaClass</literal> is a variable of type 
	  <type>MyJavaClass</type>, then 
	  <literal>myJavaClass.getName()</literal> has type 
	  <type>?String</type>.
	</para>

	<para>
	  If the Java code might indeed return &NULL;, 
	  or you are not sure, this is all good. To use the value you will 
	  have to test it against &NULL;. However there are 
	  many cases where you know the value cannot be 
	  &NULL;, for instance if this fact is specified in 
	  the Javadoc comment of the method. In that cases there are currently 
	  two possibilities. The first is to use the 
	  <link linkend="notNull"><literal>notNull</literal>
	  method</link>. 
	  So in our example <literal>notNull(myJavaClass.getName())</literal>
	  has type <type>String</type>. This solution is simple, but can 
	  be annoying if you call the same method many times, or because it 
	  makes your code less readable.
	</para>

	<para>
	  The second solution is to once and for all tell the compiler the 
	  precise type of the method (this is also useful for methods with 
	  parametric types):
	</para>

	<programlisting lang="nice">
String getName(MyJavaClass) = native String MyJavaClass.getName();</programlisting>

	<para>
          The Nice part (on the left of the <literal>=</literal> character) 
	  is the header of a method definition. Note that return type is 
	  <type>String</type> (without the optional type marker 
	  <literal>?</literal>). On the other hand, the right part says that 
	  the method is already defined in class 
	  <type>MyJavaClass</type>, with name <literal>getName</literal>,
	  the one that takes no argument and returns a 
	  <type>String</type>. With this declaration, 
	  <literal>myJavaClass.getName()</literal> has type 
	  <type>String</type>.
	</para>
      </section>
    </section>

    <section><title>Using Nice from Java</title>
      <para>
        It is possible to use libraries developed in Nice in a 
	Java program.
	Before anything, make sure that the classes generated by nicec
	can be found on your classpath when you compile the Java program
	with javac.
      </para>

      <section id="compilationMethods"><title>Calling a method</title>
        <para>
	  For <link linkend="method">methods</link> declared inside a
          class, and for those declared at the package level and whose
          first argument is a Nice class, you can simply use them as
          usual in Java.
	</para>
	<para>
	  This is not possible for methods declared at the package
          level and whose first argument is a Java class, a possibly
          null type or a primitive type.
	  You can call a such a method <literal>m</literal>
	  declared in a nice package <literal>pkg</literal>
	  by naming it <literal>pkg.dispatch.m</literal> in the Java program.
	  It does not matter in what package(s) <literal>m</literal>
	  is implemented:
	  <literal>pkg</literal> must simply be the package where the method
	  was declared.
	</para>
      </section>

      <section id="constructorFromJava"><title>Calling a constructor</title>
	<para>
	To instantiate in Java a class defined in Nice, do as usual:
	call its constructor, using the <literal>new</literal> keyword.
	Nice classes have one <link linkend="constructor">automatically 
	generated constructor</link>, 
	with one parameter for each field of the class, 
	including those inherited from Nice super-classes.
	Additionally, if some fields have default values, then a
	second constructor is generated. It only has parameters for
	the fields without a default value, and assigns to the other
	fields their default value.
	</para>
      </section>

      <section><title>Complete example</title>
      <para>
      <example><title>Using Nice from Java</title>
	<para>
	Let's see an example that illustrates all these features.
	Suppose your Nice library looks like this:
	<programlisting lang="nice">
package my.nice.pkg;

class Person
{
  String name;

  // A method:
  String display() = "Person: " + name;
}

class Worker extends Person
{
  int salary;

  display() = "Worker: " + name + " salary: " + salary;

  boolean isRich() = salary > 500;
}

	</programlisting>

	Then your Java program can create new persons and workers:
	<programlisting lang="java">
package main.java.pkg;

import my.nice.pkg.*;

public class Main
{
  public static void main(String[] args)
  {
    Person p = new Person("John");
    Worker w = new Worker("Julia", 1000);

    System.out.println(p.display());
    System.out.println(w.display());
    if (w.isRich())
      System.out.println("A well paid worker!");
  }
}
        </programlisting>
	</para>
      </example>
      </para>
      </section>

      <section><title>Optional parameters</title>
	<para>
	  Nice allows method and parameters to be 
	  <link linkend="optionalParameters">optional</link>.
	  Since this feature is not available in Java, you have to 
	  provide the value of all parameters, regardless of their
	  optionality.
	  The same applies for class fields with initializers:
	  they are ignored in the Java program, and must be given a value
	  in the call to the constructor.
        </para>
      </section>

      <section><title>Other aspects</title>
	<para>
	Fields of Nice classes are accessed normally from Java programs.
	It is possible to declare a Java subclass of a Nice class.
	The constructor will need to call the 
	<link linkend="constructorFromJava">parent constructor</link>.
	It is not fully possible to override a Nice multi-method in a Java
	program. However, provided that the method is compiled as an
	instance method, as specified <link
	linkend="compilationMethods">above</link>, you can override
	that method as usual for Java. That is, only the first
	(implicit) argument can be used to perform the override.
	</para>
      </section>

    </section>
  </chapter>

  <chapter><title>Types</title>
    <section id="optionTypes"><title>Option types</title>
      <para>
        Nice (unlike Java) makes a distinction between a type that may be &NULL;, 
        and one that may not be. So, if you want to allow &NULL; 
        <classname>String</classname>s, you write <classname>?String</classname> 
        for the type. If &NULL;s should not be allowed, you just write 
        <classname>String</classname>. It is not possible to pass a 
        <classname>?String</classname> where a <classname>String</classname> is 
        expected, unless the compiler can prove it's not &NULL;. The easiest way
        to prove that the variable is not &NULL; is to use an 
        <literal>if</literal> statement:
      </para>

<example>
  <title>Using option types</title>
<programlisting lang="nice">
	void foo(String arg) {...}
	
	void bar(?String arg) {
		if (arg != null) {
			//Here Nice knows arg is not null, so it can 
			// be passed to a method which takes a String.
			foo(arg);
		} 
		foo(arg); //Here arg may or may not be null, 
			  //so Nice gives a compilation error.
	}
</programlisting>
</example>
      <para>
        Therefore, you never have to check that all your arguments 
        aren't &NULL; again, unless you actually want to allow &NULL;s.
      </para>
      <para>
        It's important to remember that nullness inference doesn't
	work on fields of objects, only on local variables. There's
	a good reason for this: the value of an instance variable may
	have changed (updated by another thread, perhaps) between
	the time the value was checked for nullness and the time it
	is actually used. To avoid this problem, simply take a local
	reference to the field first:
      </para>
<example>
  <title>Nullness inference with fields</title>
<programlisting lang="nice">
  class Person 
  {
    ?String name
  }

  //Takes a String, not a ?String
  void printName(String name)
  {
    println(name);
  } 

  void main(String[] args) 
  {
    Person p = loadPersonFromFile(args[0]);
    let name = p.name;
    if (name == null)
      throw new Exception("Unknown person!");
    else
      //safe to call printName, we know name is a String.
      printName(name);
  }
</programlisting>
</example>

	<para id="notNull">
	  Sometimes, you know that a value cannot be &NULL;,
	  although it has an option type.
	  You can then use the <literal>notNull</literal> method to
	  assert this fact.
	  If an expression <replaceable>e</replaceable> has type
	  <type>?<replaceable>type</replaceable></type>, then
	  <literal>notNull(<replaceable>e</replaceable>)</literal>
	  has type <type>!<replaceable>type</replaceable></type>.
	  Note that if <replaceable>type</replaceable> is not a type
	  variable, <type>!<replaceable>type</replaceable></type>
	  is the same as <type><replaceable>type</replaceable></type>.
	</para>
	<para>
	  The <literal>notNull</literal> method uses 
	  <link linkend="contracts"><literal>assert</literal></link>
	  to check that the argument is not &NULL;. 
	  This means that the check will only happen at runtime
	  if <link linkend="enablingAssertions">assertion checks are
	  enabled</link>.
	  Otherwise, execution will continue, but the JVM will probably
	  fail soon afterwards with a <literal>NullPointerException</literal>
	  if the value is &NULL;, and it is used as
	  if it was not &NULL;. 
	</para>

      <para>
	There are (rare) situations where it is necessary to allow a 
	&NULL; where one shouldn't normally go, for
	instance if you need to declare a variable before entering a
	loop, but don't have a value to initialize it with. 
	You should first try to think about an alternative way of
	writing the code so that this is not needed. However, if there
	is none, a solution is to use <literal>cast(null)</literal>.
	This expression will be accepted in any context.
	It is then your responsibility to make sure that this value is
	not used.
      </para>

      <para>
        Note that <literal>notNull</literal> and <literal>cast(null)</literal>
	have completely different uses. <literal>notNull</literal> is
	used to tell the compiler that you know a certain value is not 
	&NULL;, although the type system does not guarantee it. 
	On the other hand, <literal>cast(null)</literal>
	is used to provide a non-null value which is never going to be
	used. You could not use <literal>notNull(null)</literal> for
	that purpose, because this would fail at runtime if assertion
	checks are enabled.
      </para>

      <para>
        Additional information is available on
	<ulink url="http://nice.sourceforge.net/cgi-bin/twiki/view/Doc/OptionTypes">
	the Wiki page about option types</ulink>.
      </para>

      <para>
       There is related type, which is prefixed with an exclamation point
       (<literal>!</literal>). This is used to specify a non-&NULL; type
       when it is not known if the original type allowed &NULL; or not. This
       is only needed for type parameters; for all other types,
       <type>!<replaceable>type</replaceable></type> is
       equivalent to <type><replaceable>type</replaceable></type>.
      </para>
      <para>
	For instance, in the following method:
      </para>
      <para>
       <literal><![CDATA[<T> T myMethod(Collection<T>);]]></literal>
      </para>
      <para>
       the type parameter <type>T</type> can be
       instantiated at <emphasis>any</emphasis> type, including option types
       like <type>?String</type>. If it is necessary to exclude option types
       from the domain of <type>T</type>, the type can be specified this way:
      </para>
      <para>
       <literal><![CDATA[<!T> !T myMethod(Collection<!T>);]]></literal>
      </para>
      </section>
      
      <section id="classCasting"><title>Class Casting</title>
        <para>
        Class casting is not used in Nice.  Similar to <link 
        linkend="optionTypes">Option types</link> and nullness, if the compiler
        can prove that the type of an object is compatible with the target
        context, it will allow that object to be used.  This can be done using
        the <literal>instanceof</literal> operator and an <literal>if</literal>
        statement:
        </para>
<example>
  <title>Proving the type of an object</title>
<programlisting lang="nice">
	void foo(FileOutputStream arg) {...}
	
	void bar(OutputStream arg) {
		if (arg instanceof FileOutputStream) {
			//Here Nice knows arg is a FileOutputStream, so it can 
			// be passed to a method which takes a FileOutputStream.
			foo(arg);
		} 
		foo(arg); //Here arg may or may not be a FileOutputStream, 
			  //so Nice gives a compilation error.
	}
</programlisting>
</example>
        <para>
        As with <link linkend="optionTypes">Option types</link>, type inference
        doesn't work on fields of objects or on method calls, only on local
        variables. There's a good reason for this: the value of an instance 
        variable may have changed (updated by another thread, perhaps) between
        the time the value was checked for its type and the time it is actually
        used. Similarly, method calls can return objects of different sub-types
        every time they are called.  To avoid this problem, simply assign the
        value to a local variable first.
        </para>
      </section>

      <section id = "typeParameters"><title>Type Parameters</title>
        <para>
          Classes and methods can be parameterized with type
          variables in Nice as is demonstrated in each of their respective
          chapters. In addition to the ability to introduce type variables,
          Nice provides the ability to constrain those types in certain ways.
          <link linkend="optionTypes">Option types</link> are one such constraint.
        </para>
        <para>
          Simple type parameters of the form
        </para>
        <para>
          <type>&LT;<replaceable>type-variable</replaceable></type>
	  <optional><type>, <replaceable>type-variable</replaceable> ...</type>
	  </optional><type>&GT;</type>
        </para>
        <para>
          are commonly encountered in Nice, but are a simplified form of a more
          general syntax. <type>&lt;T&gt;</type> is actually shorthand for
          <type>&lt;Any T&gt;</type>, which says that <type>T</type> may be any 
          type at all. It is possible to constrain <type>T</type> so that it 
          must be a subtype of some other type. This example shows that
          <literal>filter</literal> may be implemented for any type 
          <type>T</type>, but <type>C</type> must be a subclass of Collection.
        </para>
        <para>
          <literal>
<![CDATA[<Collection C, T> C<T> filter(C<T>, T->boolean);]]>
          </literal>
        </para>
        <para>
          It's also possible to enforce some relation among the type parameters,
          such that one must be a subtype of the other, as in this example from
          the standard library, which can be read as "Any T and U, so long as U
          is a subtype of T".
        </para>
        <para>
          <literal>
<![CDATA[<T, U | U <: T> U[] fill(T[] array, int->U value)]]>
          </literal>
        </para>
        <para>
         Note the notation <literal>&lt;T | T &lt;: SomeType &gt;</literal> means the
         same thing as <literal>&lt;SomeType T&gt;</literal>.
        </para>
        <para>
          There is also a notation for the same class as the declaring class
	  of a method: <type>alike</type>.
	  For instance, the following class <type>Foo</type> declares
	   a method <literal>copy</literal>, such that 
	   <literal>x.copy()</literal>
	  has the same type as <literal>x</literal>, <literal>x</literal> 
	  being of any subclass of <type>Foo</type>.
        </para>
        <para>
	<example id="ex:copy"><title>A copy method with an exact type</title>
	<programlisting lang="nice">
class Foo
{
  String value;

  alike copy();
}

copy(#Foo f) = new Foo(value: f.value);

class Bar extends Foo
{
  int id;
}

copy(#Bar b) = new Bar(value: b.value, id: generateNewId());
</programlisting>
        </example>
	</para>
        <para>
          Note that <link linkend="exactMatching">exact matching</link>
	  is required to implement the
	  <literal>copy</literal> method.
        </para>
      </section>
      <section id = "abstractInterfaces">
        <title>Abstract Interfaces</title>
        <para>
          Nice offers a powerful tool known as the <firstterm>abstract interface</firstterm>. 
          Abstract interfaces are similar in some respects to regular
          Java- or Nice-style interfaces in that they define a set of methods that
          a type must implement to be considered a member of the interface.
        </para>
        <para>
          Two things make an abstract interface different from a regular interface.
          First, a class can be made to implement an abstract interface <emphasis>after</emphasis>
          it's been defined, and even the source code is unnecessary. You can make
          the basic <literal>String</literal> class implement your new
	  abstract interface, if you like.
          Second, an abstract interface is not actually a type, it's an annotation
          which can be applied to types. This means that when you declare an abstract
          interface, you're not creating a new type, you're saying "types which implement
          this abstract interface will all have these methods", but those types are
          not related in any other way. So it is not possible to make a <literal>
          List&lt;MyAbstractInterface&gt;</literal>, or to use an abstract interface
          as a type declaration like <literal>var MyAbstractInterface absInter = ...
          </literal>.
        </para>
        <para>
          So what is an abstract interface <emphasis>for</emphasis>? Abstract interfaces
          can appear in type parameters, so one can write methods for them:
        </para>
        <para>
         <literal>&lt;MyAbstractInterface T&gt; void doSomething(T thing);</literal>
        </para>
        <para>
         and then apply these methods to any object whose class implements <literal>
         MyAbstractInterface</literal>. It's especially useful for situations where
         one wants to use a method on a group of unrelated types, as in the example 
         below. We have a <literal>log()</literal> method which is parameterized
         for any class which implements the abstract interface <literal>LogEntry</literal>,
         and we make a number of classes implement
	 <literal>LogEntry</literal>, so they can be passed to our log method.
        </para>
        <para>
	<example id="ex:abstractInterface"><title>Abstract Interfaces</title>
	<programlisting lang="nice"><![CDATA[
//Abstract interface for things which can be logged.
abstract interface LogEntry
{
  String toLogString();
  int severity();
}

//Some constants for severity levels
let int DEBUG = 1;
let int INFO = 2;
let int ERROR = 3;

<LogEntry E> void log(E entry, int severity = -1) 
{
  if (severity < 0)
    severity = entry.severity();
  someLogWriter.println(timeStamp() + " " + severity + " " + entry.toLogString());
}

//Make strings pass straight through as DEBUG info.
class java.lang.String implements LogEntry;

toLogString(String s) = s;
severity(String s) = DEBUG;


//Make throwables print a stack trace, plus a message
class nice.lang.Throwable implements LogEntry;

toLogString(Throwable t) 
{
  let writer = new StringWriter();
  let printWriter = new PrintWriter(writer);
  printWriter.println("ERROR: " + t.getClass().getName() + ": " + t.getMessage());
  t.printStackTrace(printWriter);
  printWriter.close();
  return writer.toString();
}

severity(Throwable t) = ERROR;

//We like to log requests, too
class javax.servlet.http.HttpServletRequest implements LogEntry;

toLogString(HttpServletRequest r) = "Request from: " + r.getRemoteHost();
severity(HttpServletRequest r) = INFO;

]]>
</programlisting>
        </example>
        </para>
        <para>
          There are some interesting things to notice about this code. First, 
          we only had to write <literal>log()</literal> once, and we left it
          up to the LogEntry to do the formatting. This could be done with a
          regular interface as well, except that we also made String and 
          Throwable implement our abstract interface, which we couldn't have 
          done with a regular interface. So now we can write code like
        </para>
        <para>
          <programlisting lang="nice">
            log(request);
            log("Beginning processing");
            try 
              {
                1/0;
              } 
            catch (Exception e)
              {
                log(e);
              }
          </programlisting>
        </para>
        <para>
          and our abstract interface implementations will take care of making
          sure that we get the right formatting and severity levels. The most
          interesting thing about this code is that if we write <literal>log(5)
          </literal> then the compiler will catch the error, because <literal>
          byte</literal> doesn't implement <literal>LogEntry</literal>. If
          we had defined <literal>log</literal> with the signature <literal>
          &lt;E&gt; void log(E entry, int severity = -1)</literal>, we could 
          have achieved all the same effects, but we would have lost the
          type safety abstract interfaces gave us above - because
	  <literal>&lt;E&gt;</literal> means <emphasis>any</emphasis>
	  type is allowed, so we would have had to define some defaults:
        </para>
        <para>
          <programlisting lang="nice">
            toLogString(e)
            {
              throw new Exception("No toLogString method defined!");
            }

            severity(e)
            {
              throw new Exception("No severity method defined!");
            }
          </programlisting>
        </para>
        <para>
          Then we'd be no better off than in a dynamically typed language -
          we wouldn't find out that we'd tried to log an integer until we got an
          exception at runtime. With abstract interfaces, we were able to
          tell the compiler <emphasis>exactly</emphasis> which classes 
          should be allowed as arguments to <literal>log</literal>, and so
          our program is safer as a result.
        </para>
        <para>
          Daniel Bonniot, Nice's creator, invented abstract interfaces. You 
          can read more about them in the 
          <ulink url = "http://nice.sourceforge.net/research.html">Academic
          Research</ulink> section of the Nice website.
        </para>

      </section>      

  </chapter>
  

</book>

<!--
  Local Variables:
  sgml-validate-command: "xmllint -noout -valid"
  End:
 -->