summaryrefslogtreecommitdiffstats
path: root/runtime/doc/vim9class.txt
blob: ba821c1b29db42a348959e145356a91eb82908df (plain)
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
*vim9class.txt*	For Vim version 9.1.  Last change: 2024 Jan 12


		  VIM REFERENCE MANUAL	  by Bram Moolenaar


Vim9 classes, objects, interfaces, types and enums.		*vim9-class*

1.  Overview			|Vim9-class-overview|
2.  A simple class		|Vim9-simple-class|
3.  Class variables and methods	|Vim9-class-member|
4.  Using an abstract class	|Vim9-abstract-class|
5.  Using an interface		|Vim9-using-interface|
6.  More class details		|Vim9-class|
7.  Type definition		|Vim9-type|
8.  Enum			|Vim9-enum|

9.  Rationale
10. To be done later

==============================================================================

1. Overview					*Vim9-class-overview*

The fancy term is "object-oriented programming".  You can find lots of study
material on this subject.  Here we document what |Vim9| script provides,
assuming you know the basics already.  Added are helpful hints about how to
use this functionality effectively.  Vim9 classes and objects cannot be used
in legacy Vim scripts and legacy functions.

The basic item is an object:
- An object stores state.  It contains one or more variables that can each
  have a value.
- An object provides functions that use and manipulate its state.  These
  functions are invoked "on the object", which is what sets it apart from the
  traditional separation of data and code that manipulates the data.
- An object has a well defined interface, with typed member variables and
  methods.
- Objects are created from a class and all objects have the same interface.
  This does not change at runtime, it is not dynamic.

An object can only be created by a class.  A class provides:
- A new() method, the constructor, which returns an object for the class.
  This method is invoked on the class name: MyClass.new().
- State shared by all objects of the class: class variables (class members).
- A hierarchy of classes, with super-classes and sub-classes, inheritance.

An interface is used to specify properties of an object:
- An object can declare several interfaces that it implements.
- Different objects implementing the same interface can be used the same way.

The class hierarchy allows for single inheritance.  Otherwise interfaces are
to be used where needed.


Class modeling ~

You can model classes any way you like.  Keep in mind what you are building,
don't try to model the real world.  This can be confusing, especially because
teachers use real-world objects to explain class relations and you might think
your model should therefore reflect the real world.  It doesn't!  The model
should match your purpose.

Keep in mind that composition (an object contains other objects) is often
better than inheritance (an object extends another object).  Don't waste time
trying to find the optimal class model.  Or waste time discussing whether a
square is a rectangle or that a rectangle is a square.  It doesn't matter.


==============================================================================

2.  A simple class				*Vim9-simple-class*

Let's start with a simple example: a class that stores a text position (see
below for how to do this more efficiently): >

	class TextPosition
	   var lnum: number
	   var col: number

	   def new(lnum: number, col: number)
	      this.lnum = lnum
	      this.col = col
	   enddef

	   def SetLnum(lnum: number)
	      this.lnum = lnum
	   enddef

	   def SetCol(col: number)
	      this.col = col
	   enddef

	   def SetPosition(lnum: number, col: number)
	      this.lnum = lnum
	      this.col = col
	   enddef
	 endclass
<							*object* *Object*
You can create an object from this class with the new() method: >

	var pos = TextPosition.new(1, 1)
<
The object variables "lnum" and "col" can be accessed directly: >

	echo $'The text position is ({pos.lnum}, {pos.col})'
<						    *E1317* *E1327* *:this*
If you have been using other object-oriented languages you will notice that in
Vim, within a class definition, the declared object members are consistently
referred to with the "this." prefix.  This is different from languages like
Java and TypeScript.  The naming convention makes the object members easy to
spot.  Also, when a variable does not have the "this." prefix you know it is
not an object variable.
								*E1411*
From outside the class definition, access an object's methods and variables by
using the object name followed by a dot following by the member: >

	pos.lnum
	pos.SetCol(10)
<
							*E1405* *E1406*
A class name cannot be used as an expression.  A class name cannot be used in
the left-hand-side of an assignment.


Object variable write access ~
						    *read-only-variable*
Now try to change an object variable directly: >

	pos.lnum = 9
<							*E1335*
This will give you an error!  That is because by default object variables can
be read but not set.  That's why the TextPosition class provides a method for
it: >

	pos.SetLnum(9)

Allowing to read but not set an object variable is the most common and safest
way.  Most often there is no problem using a value, while setting a value may
have side effects that need to be taken care of.  In this case, the SetLnum()
method could check if the line number is valid and either give an error or use
the closest valid value.
					*:public* *public-variable* *E1331*
If you don't care about side effects and want to allow the object variable to
be changed at any time, you can make it public: >

	public var lnum: number
	public var col: number

Now you don't need the SetLnum(), SetCol() and SetPosition() methods, setting
"pos.lnum" directly above will no longer give an error.
							*E1326*
If you try to set an object variable that doesn't exist you get an error: >
	pos.other = 9
<	E1326: Member not found on object "TextPosition": other ~

							*E1376*
A object variable cannot be accessed using the class name.

Protected variables ~
					*protected-variable* *E1332* *E1333*
On the other hand, if you do not want the object variables to be read directly
from outside the class or its sub-classes, you can make them protected.  This
is done by prefixing an underscore to the name: >

	var _lnum: number
	var _col: number

Now you need to provide methods to get the value of the protected variables.
These are commonly called getters.  We recommend using a name that starts with
"Get": >

	def GetLnum(): number
	   return this._lnum
	enddef

	def GetCol(): number
	   return this._col
	enddef

This example isn't very useful, the variables might as well have been public.
It does become useful if you check the value.  For example, restrict the line
number to the total number of lines: >

	def GetLnum(): number
	   if this._lnum > this._lineCount
	      return this._lineCount
	   endif
	   return this._lnum
	enddef
<
Protected methods ~
						*protected-method* *E1366*
If you want object methods to be accessible only from other methods of the
same class and not used from outside the class, then you can make them
protected.  This is done by prefixing the method name with an underscore: >

    class SomeClass
	def _Foo(): number
	  return 10
	enddef
	def Bar(): number
	  return this._Foo()
	enddef
    endclass
<
Accessing a protected method outside the class will result in an error (using
the above class): >

    var a = SomeClass.new()
    a._Foo()
<
Simplifying the new() method ~
						*new()* *constructor*
See also |default-constructor| and |multiple-constructors|.

Many constructors take values for the object variables.  Thus you very often
see this pattern: >

	 class SomeClass
	   var lnum: number
	   var col: number

	   def new(lnum: number, col: number)
	      this.lnum = lnum
	      this.col = col
	   enddef
	 endclass
<
							*E1390*
Not only is this text you need to write, it also has the type of each
variable twice.  Since this is so common a shorter way to write new() is
provided: >

	   def new(this.lnum, this.col)
	   enddef

The semantics are easy to understand: Providing the object variable name,
including "this.", as the argument to new() means the value provided in the
new() call is assigned to that object variable.  This mechanism comes from the
Dart language.

Putting together this way of using new() and making the variables public
results in a much shorter class definition than what we started with: >

	class TextPosition
	   public var lnum: number
	   public var col: number

	   def new(this.lnum, this.col)
	   enddef

	   def SetPosition(lnum: number, col: number)
	      this.lnum = lnum
	      this.col = col
	   enddef
	 endclass

The sequence of constructing a new object is:
1. Memory is allocated and cleared.  All values are zero/false/empty.
2. For each declared object variable that has an initializer, the expression
   is evaluated and assigned to the variable.  This happens in the sequence
   the variables are declared in the class.
3. Arguments in the new() method in the "this.name" form are assigned.
4. The body of the new() method is executed.

If the class extends a parent class, the same thing happens.  In the second
step the object variables of the parent class are initialized first.  There is
no need to call "super()" or "new()" on the parent.

							*E1365*
When defining the new() method the return type should not be specified.  It
always returns an object of the class.

							*E1386*
When invoking an object method, the method name should be preceded by the
object variable name.  An object method cannot be invoked using the class
name.

==============================================================================

3.  Class Variables and Methods			*Vim9-class-member*

					    *:static* *E1337* *E1338* *E1368*
Class members are declared with "static".  They are used by the name without a
prefix in the class where they are defined: >

	class OtherThing
	   var size: number
	   static var totalSize: number

	   def new(this.size)
	      totalSize += this.size
	   enddef
	endclass
<							*E1340* *E1341*
Since the name is used as-is, shadowing the name by a method argument name
or local variable name is not allowed.

					    *E1374* *E1375* *E1384* *E1385*
To access a class member outside of the class where it is defined, the class
name prefix must be used.  A class member cannot be accessed using an object.

Just like object members the access can be made protected by using an
underscore as the first character in the name, and it can be made public by
prefixing "public": >

    class OtherThing
	static var total: number	  # anybody can read, only class can write
	static var _sum: number	          # only class can read and write
	public static var result: number  # anybody can read and write
    endclass
<
							*class-method*
Class methods are also declared with "static".  They can use the class
variables but they have no access to the object variables, they cannot use the
"this" keyword:
>
	class OtherThing
	   var size: number
	   static var totalSize: number

	   # Clear the total size and return the value it had before.
	   static def ClearTotalSize(): number
	      var prev = totalSize
	      totalSize = 0
	      return prev
	   enddef
	endclass

Inside the class the class method can be called by name directly, outside the
class the class name must be prefixed: `OtherThing.ClearTotalSize()`.  To use
a class method from a parent class in a child class, the class name must be
prefixed.

Just like object methods the access can be made protected by using an
underscore as the first character in the method name: >

    class OtherThing
	static def _Foo()
	    echo "Foo"
	enddef
	def Bar()
	    _Foo()
	enddef
    endclass
<
							*E1370*
Note that constructors cannot be declared as "static". They are called like a
static but execute as an object method; they have access to "this".

To access the class methods and class variables of a super class in an
extended class, the class name prefix should be used just as from anywhere
outside of the defining class: >

    vim9script
    class Vehicle
	static var nextID: number = 1000
	static def GetID(): number
	    nextID += 1
	    return nextID
	enddef
    endclass
    class Car extends Vehicle
	var myID: number
	def new()
	    this.myID = Vehicle.GetID()
	enddef
    endclass
<
Class variables and methods are not inherited by a child class.  A child class
can declare a static variable or a method with the same name as the one in the
super class.  Depending on the class where the member is used the
corresponding class member will be used.  The type of the class member in a
child class can be different from that in the super class.

The double underscore (__) prefix for a class or object method name is
reserved for future use.

					*object-final-variable* *E1409*
The |:final| keyword can be used to make a class or object variable a
constant.  Examples: >

    class A
	final v1 = [1, 2]		# final object variable
	public final v2 = {x: 1}	# final object variable
	static final v3 = 'abc'		# final class variable
	public static final v4 = 0z10	# final class variable
    endclass
<
A final variable can be changed only from a constructor function.  Example: >

    class A
	final v1: list<number>
	def new()
	    this.v1 = [1, 2]
	enddef
    endclass
    var a = A.new()
    echo a.v1
<
Note that the value of a final variable can be changed.  Example: >

    class A
	public final v1 = [1, 2]
    endclass
    var a = A.new()
    a.v1[0] = 6			# OK
    a.v1->add(3)		# OK
    a.v1 = [3, 4]		# Error
<
							*E1408*
Final variables are not supported in an interface.  A class or object method
cannot be final.

					*object-const-variable*
The |:const| keyword can be used to make a class or object variable and the
value a constant.  Examples: >

    class A
	const v1 = [1, 2]		# const object variable
	public const v2 = {x: 1}	# const object variable
	static const v3 = 'abc'		# const class variable
	public static const v4 = 0z10	# const class variable
    endclass
<
A const variable can be changed only from a constructor function. Example: >

    class A
	const v1: list<number>
	def new()
	    this.v1 = [1, 2]
	enddef
    endclass
    var a = A.new()
    echo a.v1
<
A const variable and its value cannot be changed.  Example: >

    class A
	public const v1 = [1, 2]
    endclass
    var a = A.new()
    a.v1[0] = 6			# Error
    a.v1->add(3)		# Error
    a.v1 = [3, 4]		# Error
<
							 *E1410*
Const variables are not supported in an interface.  A class or object method
cannot be a const.

==============================================================================

4.  Using an abstract class			*Vim9-abstract-class*

An abstract class forms the base for at least one sub-class.  In the class
model one often finds that a few classes have the same properties that can be
shared, but a class with these properties does not have enough state to create
an object from.  A sub-class must extend the abstract class and add the
missing state and/or methods before it can be used to create objects for.

For example, a Shape class could store a color and thickness.  You cannot
create a Shape object, it is missing the information about what kind of shape
it is.  The Shape class functions as the base for a Square and a Triangle
class, for which objects can be created.  Example: >

	abstract class Shape
	   var color = Color.Black
	   var thickness = 10
	endclass

	class Square extends Shape
	   var size: number

	   def new(this.size)
	   enddef
	endclass

	class Triangle extends Shape
	   var base: number
	   var height: number

	   def new(this.base, this.height)
	   enddef
	endclass
<
An abstract class is defined the same way as a normal class, except that it
does not have any new() method. *E1359*

					    *abstract-method* *E1371* *E1372*
An abstract method can be defined in an abstract class by using the "abstract"
prefix when defining the method: >

	abstract class Shape
	   abstract def Draw()
	endclass
<
A static method in an abstract class cannot be an abstract method.

						*E1373*
A non-abstract class extending the abstract class must implement all the
abstract methods.  The signature (arguments, argument types and return type)
must be exactly the same.  If the return type of a method is a c