blob: 4dc67bd8723fea6e0b5ac77cca0228e36ff5834b [file] [log] [blame]
Dominique Pellé17dca3c2023-12-14 20:36:32 +01001*vim9class.txt* For Vim version 9.0. Last change: 2023 Dec 14
Bram Moolenaarc1c365c2022-12-04 20:13:24 +00002
3
4 VIM REFERENCE MANUAL by Bram Moolenaar
5
6
Bram Moolenaarbe4e0162023-02-02 13:59:48 +00007NOTE - This is not finished yet, anything can still change! - NOTE
Bram Moolenaarc1c365c2022-12-04 20:13:24 +00008
9
10Vim9 classes, objects, interfaces, types and enums.
11
121. Overview |Vim9-class-overview|
132. A simple class |Vim9-simple-class|
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200143. Class variables and methods |Vim9-class-member|
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000154. Using an abstract class |Vim9-abstract-class|
165. Using an interface |Vim9-using-interface|
176. More class details |Vim9-class|
187. Type definition |Vim9-type|
198. Enum |Vim9-enum|
Bram Moolenaarc1c365c2022-12-04 20:13:24 +000020
219. Rationale
2210. To be done later
23
24==============================================================================
25
261. Overview *Vim9-class-overview*
27
28The fancy term is "object-oriented programming". You can find lots of study
Bram Moolenaarbe4e0162023-02-02 13:59:48 +000029material on this subject. Here we document what |Vim9| script provides,
30assuming you know the basics already. Added are helpful hints about how to
Yegappan Lakshmanan0ab500d2023-10-21 11:59:42 +020031use this functionality effectively. Vim9 classes and objects cannot be used
32in legacy Vim scripts and legacy functions.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +000033
34The basic item is an object:
35- An object stores state. It contains one or more variables that can each
36 have a value.
Bram Moolenaarbe4e0162023-02-02 13:59:48 +000037- An object provides functions that use and manipulate its state. These
Bram Moolenaarc1c365c2022-12-04 20:13:24 +000038 functions are invoked "on the object", which is what sets it apart from the
39 traditional separation of data and code that manipulates the data.
40- An object has a well defined interface, with typed member variables and
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -070041 methods.
Bram Moolenaarbe4e0162023-02-02 13:59:48 +000042- Objects are created from a class and all objects have the same interface.
43 This does not change at runtime, it is not dynamic.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +000044
45An object can only be created by a class. A class provides:
46- A new() method, the constructor, which returns an object for the class.
47 This method is invoked on the class name: MyClass.new().
Bram Moolenaarbe4e0162023-02-02 13:59:48 +000048- State shared by all objects of the class: class variables (class members).
Bram Moolenaarc1c365c2022-12-04 20:13:24 +000049- A hierarchy of classes, with super-classes and sub-classes, inheritance.
50
51An interface is used to specify properties of an object:
52- An object can declare several interfaces that it implements.
53- Different objects implementing the same interface can be used the same way.
54
55The class hierarchy allows for single inheritance. Otherwise interfaces are
56to be used where needed.
57
58
59Class modeling ~
60
61You can model classes any way you like. Keep in mind what you are building,
62don't try to model the real world. This can be confusing, especially because
63teachers use real-world objects to explain class relations and you might think
64your model should therefore reflect the real world. It doesn't! The model
65should match your purpose.
66
Bram Moolenaarbe4e0162023-02-02 13:59:48 +000067Keep in mind that composition (an object contains other objects) is often
68better than inheritance (an object extends another object). Don't waste time
69trying to find the optimal class model. Or waste time discussing whether a
70square is a rectangle or that a rectangle is a square. It doesn't matter.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +000071
72
73==============================================================================
74
752. A simple class *Vim9-simple-class*
76
Bram Moolenaarbe4e0162023-02-02 13:59:48 +000077Let's start with a simple example: a class that stores a text position (see
78below for how to do this more efficiently): >
Bram Moolenaarc1c365c2022-12-04 20:13:24 +000079
80 class TextPosition
Doug Kearns74da0ee2023-12-14 20:26:26 +010081 var lnum: number
82 var col: number
Bram Moolenaarc1c365c2022-12-04 20:13:24 +000083
84 def new(lnum: number, col: number)
85 this.lnum = lnum
86 this.col = col
87 enddef
88
89 def SetLnum(lnum: number)
90 this.lnum = lnum
91 enddef
92
93 def SetCol(col: number)
94 this.col = col
95 enddef
96
97 def SetPosition(lnum: number, col: number)
98 this.lnum = lnum
99 this.col = col
100 enddef
101 endclass
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000102< *object* *Object*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000103You can create an object from this class with the new() method: >
104
105 var pos = TextPosition.new(1, 1)
106
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700107The object variables "lnum" and "col" can be accessed directly: >
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000108
109 echo $'The text position is ({pos.lnum}, {pos.col})'
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000110< *E1317* *E1327*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000111If you have been using other object-oriented languages you will notice that
112in Vim the object members are consistently referred to with the "this."
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000113prefix. This is different from languages like Java and TypeScript. The
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000114naming convention makes the object members easy to spot. Also, when a
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700115variable does not have the "this." prefix you know it is not an object
116variable.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000117
118
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700119Object variable write access ~
Ernie Rael03042a22023-11-11 08:53:32 +0100120 *read-only-variable*
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700121Now try to change an object variable directly: >
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000122
123 pos.lnum = 9
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000124< *E1335*
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700125This will give you an error! That is because by default object variables can
126be read but not set. That's why the TextPosition class provides a method for
127it: >
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000128
129 pos.SetLnum(9)
130
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700131Allowing to read but not set an object variable is the most common and safest
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000132way. Most often there is no problem using a value, while setting a value may
133have side effects that need to be taken care of. In this case, the SetLnum()
134method could check if the line number is valid and either give an error or use
135the closest valid value.
Ernie Rael03042a22023-11-11 08:53:32 +0100136 *:public* *public-variable* *E1331*
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700137If you don't care about side effects and want to allow the object variable to
138be changed at any time, you can make it public: >
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000139
140 public this.lnum: number
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000141 public this.col: number
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000142
143Now you don't need the SetLnum(), SetCol() and SetPosition() methods, setting
144"pos.lnum" directly above will no longer give an error.
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200145 *E1326*
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700146If you try to set an object variable that doesn't exist you get an error: >
Bram Moolenaarf1dcd142022-12-31 15:30:45 +0000147 pos.other = 9
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200148< E1326: Member not found on object "TextPosition": other ~
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000149
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200150 *E1376*
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700151A object variable cannot be accessed using the class name.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000152
Ernie Rael03042a22023-11-11 08:53:32 +0100153Protected variables ~
154 *protected-variable* *E1332* *E1333*
155On the other hand, if you do not want the object variables to be read directly
156from outside the class or its sub-classes, you can make them protected. This
157is done by prefixing an underscore to the name: >
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000158
Doug Kearns74da0ee2023-12-14 20:26:26 +0100159 var _lnum: number
160 var _col number
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000161
Ernie Rael03042a22023-11-11 08:53:32 +0100162Now you need to provide methods to get the value of the protected variables.
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000163These are commonly called getters. We recommend using a name that starts with
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000164"Get": >
165
166 def GetLnum(): number
167 return this._lnum
168 enddef
169
170 def GetCol() number
171 return this._col
172 enddef
173
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700174This example isn't very useful, the variables might as well have been public.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000175It does become useful if you check the value. For example, restrict the line
176number to the total number of lines: >
177
178 def GetLnum(): number
179 if this._lnum > this._lineCount
180 return this._lineCount
181 endif
182 return this._lnum
183 enddef
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200184<
Ernie Rael03042a22023-11-11 08:53:32 +0100185Protected methods ~
186 *protected-method* *E1366*
Yegappan Lakshmanancd7293b2023-08-27 19:18:23 +0200187If you want object methods to be accessible only from other methods of the
188same class and not used from outside the class, then you can make them
Ernie Rael03042a22023-11-11 08:53:32 +0100189protected. This is done by prefixing the method name with an underscore: >
Yegappan Lakshmanancd7293b2023-08-27 19:18:23 +0200190
191 class SomeClass
192 def _Foo(): number
193 return 10
194 enddef
195 def Bar(): number
196 return this._Foo()
197 enddef
198 endclass
199<
Ernie Rael03042a22023-11-11 08:53:32 +0100200Accessing a protected method outside the class will result in an error (using
Yegappan Lakshmanancd7293b2023-08-27 19:18:23 +0200201the above class): >
202
203 var a = SomeClass.new()
204 a._Foo()
205<
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000206Simplifying the new() method ~
Yegappan Lakshmanan413f8392023-09-28 22:46:37 +0200207 *new()* *constructor*
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700208Many constructors take values for the object variables. Thus you very often
209see this pattern: >
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000210
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000211 class SomeClass
Doug Kearns74da0ee2023-12-14 20:26:26 +0100212 var lnum: number
213 var col: number
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000214
215 def new(lnum: number, col: number)
216 this.lnum = lnum
217 this.col = col
218 enddef
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000219 endclass
h-eastdb385522023-09-28 22:18:19 +0200220<
221 *E1390*
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700222Not only is this text you need to write, it also has the type of each
Dominique Pellé17dca3c2023-12-14 20:36:32 +0100223variable twice. Since this is so common a shorter way to write new() is
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700224provided: >
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000225
226 def new(this.lnum, this.col)
227 enddef
228
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700229The semantics are easy to understand: Providing the object variable name,
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000230including "this.", as the argument to new() means the value provided in the
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700231new() call is assigned to that object variable. This mechanism comes from the
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000232Dart language.
233
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700234Putting together this way of using new() and making the variables public
235results in a much shorter class definition than what we started with: >
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000236
237 class TextPosition
Doug Kearns74da0ee2023-12-14 20:26:26 +0100238 public var lnum: number
239 public var col: number
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000240
241 def new(this.lnum, this.col)
242 enddef
243
244 def SetPosition(lnum: number, col: number)
245 this.lnum = lnum
246 this.col = col
247 enddef
248 endclass
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000249
250The sequence of constructing a new object is:
2511. Memory is allocated and cleared. All values are zero/false/empty.
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -07002522. For each declared object variable that has an initializer, the expression
253 is evaluated and assigned to the variable. This happens in the sequence
254 the variables are declared in the class.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +00002553. Arguments in the new() method in the "this.name" form are assigned.
2564. The body of the new() method is executed.
257
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000258If the class extends a parent class, the same thing happens. In the second
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700259step the object variables of the parent class are initialized first. There is
260no need to call "super()" or "new()" on the parent.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000261
Yegappan Lakshmananb90e3bc2023-09-28 23:06:48 +0200262 *E1365*
Yegappan Lakshmanan6ac15442023-08-20 18:20:17 +0200263When defining the new() method the return type should not be specified. It
264always returns an object of the class.
265
Yegappan Lakshmananb90e3bc2023-09-28 23:06:48 +0200266 *E1386*
267When invoking an object method, the method name should be preceded by the
Dominique Pellé17dca3c2023-12-14 20:36:32 +0100268object variable name. An object method cannot be invoked using the class
Yegappan Lakshmananb90e3bc2023-09-28 23:06:48 +0200269name.
270
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000271==============================================================================
272
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +02002733. Class Variables and Methods *Vim9-class-member*
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000274
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200275 *:static* *E1337* *E1338* *E1368*
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000276Class members are declared with "static". They are used by the name without a
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200277prefix in the class where they are defined: >
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000278
279 class OtherThing
Doug Kearns74da0ee2023-12-14 20:26:26 +0100280 var size: number
281 static var totalSize: number
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000282
283 def new(this.size)
284 totalSize += this.size
285 enddef
286 endclass
287< *E1340* *E1341*
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700288Since the name is used as-is, shadowing the name by a method argument name
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000289or local variable name is not allowed.
290
Yegappan Lakshmananb90e3bc2023-09-28 23:06:48 +0200291 *E1374* *E1375* *E1384* *E1385*
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200292To access a class member outside of the class where it is defined, the class
293name prefix must be used. A class member cannot be accessed using an object.
294
Ernie Rael03042a22023-11-11 08:53:32 +0100295Just like object members the access can be made protected by using an
296underscore as the first character in the name, and it can be made public by
297prefixing "public": >
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000298
299 class OtherThing
Doug Kearns74da0ee2023-12-14 20:26:26 +0100300 static var total: number # anybody can read, only class can write
301 static var _sum: number # only class can read and write
302 public static var result: number # anybody can read and write
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000303 endclass
304<
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200305 *class-method*
306Class methods are also declared with "static". They can use the class
307variables but they have no access to the object variables, they cannot use the
h_eastba77bbb2023-10-03 04:47:13 +0900308"this" keyword:
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200309>
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000310 class OtherThing
Doug Kearns74da0ee2023-12-14 20:26:26 +0100311 var size: number
312 static var totalSize: number
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000313
314 # Clear the total size and return the value it had before.
315 static def ClearTotalSize(): number
316 var prev = totalSize
317 totalSize = 0
318 return prev
319 enddef
320 endclass
321
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200322Inside the class the class method can be called by name directly, outside the
323class the class name must be prefixed: `OtherThing.ClearTotalSize()`. To use
324a super class method in a child class, the class name must be prefixed.
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000325
Ernie Rael03042a22023-11-11 08:53:32 +0100326Just like object methods the access can be made protected by using an
327underscore as the first character in the method name: >
Yegappan Lakshmanancd7293b2023-08-27 19:18:23 +0200328
329 class OtherThing
330 static def _Foo()
331 echo "Foo"
332 enddef
333 def Bar()
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200334 _Foo()
Yegappan Lakshmanancd7293b2023-08-27 19:18:23 +0200335 enddef
336 endclass
Gianmaria Bajo4b9777a2023-08-29 22:26:30 +0200337<
338 *E1370*
339Note that constructors cannot be declared as "static", because they always
340are.
Yegappan Lakshmanancd7293b2023-08-27 19:18:23 +0200341
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200342To access the class methods and class variables of a super class in an
343extended class, the class name prefix should be used just as from anywhere
344outside of the defining class: >
345
346 vim9script
347 class Vehicle
Doug Kearns74da0ee2023-12-14 20:26:26 +0100348 static var nextID: number = 1000
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200349 static def GetID(): number
350 nextID += 1
351 return nextID
352 enddef
353 endclass
354 class Car extends Vehicle
Doug Kearns74da0ee2023-12-14 20:26:26 +0100355 var myID: number
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200356 def new()
357 this.myID = Vehicle.GetID()
358 enddef
359 endclass
360<
361Class variables and methods are not inherited by a child class. A child class
362can declare a static variable or a method with the same name as the one in the
363super class. Depending on the class where the member is used the
364corresponding class member will be used. The type of the class member in a
365child class can be different from that in the super class.
366
Yegappan Lakshmanane5437c52023-12-16 14:11:19 +0100367 *object-final-variable* *E1409*
368The |:final| keyword can be used to make a class or object variable a
369constant. Examples: >
370
371 class A
372 final v1 = [1, 2] # final object variable
373 public final v2 = {x: 1} # final object variable
374 static final v3 = 'abc' # final class variable
375 public static final v4 = 0z10 # final class variable
376 endclass
377<
378A final variable can be changed only from a constructor function. Example: >
379
380 class A
381 final v1: list<number>
382 def new()
383 this.v1 = [1, 2]
384 enddef
385 endclass
386 var a = A.new()
387 echo a.v1
388<
389Note that the value of a final variable can be changed. Example: >
390
391 class A
392 public final v1 = [1, 2]
393 endclass
394 var a = A.new()
395 a.v1[0] = 6 # OK
396 a.v1->add(3) # OK
397 a.v1 = [3, 4] # Error
398<
399 *E1408*
400Final variables are not supported in an interface. A class or object method
401cannot be final.
402
403 *object-const-variable*
404The |:const| keyword can be used to make a class or object variable and the
405value a constant. Examples: >
406
407 class A
408 const v1 = [1, 2] # const object variable
409 public const v2 = {x: 1} # const object variable
410 static const v3 = 'abc' # const class variable
411 public static const v4 = 0z10 # const class variable
412 endclass
413<
414A const variable can be changed only from a constructor function. Example: >
415
416 class A
417 const v1: list<number>
418 def new()
419 this.v1 = [1, 2]
420 enddef
421 endclass
422 var a = A.new()
423 echo a.v1
424<
425A const variable and its value cannot be changed. Example: >
426
427 class A
428 public const v1 = [1, 2]
429 endclass
430 var a = A.new()
431 a.v1[0] = 6 # Error
432 a.v1->add(3) # Error
433 a.v1 = [3, 4] # Error
434<
435 *E1410*
436Const variables are not supported in an interface. A class or object method
437cannot be a const.
438
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000439==============================================================================
440
4414. Using an abstract class *Vim9-abstract-class*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000442
443An abstract class forms the base for at least one sub-class. In the class
444model one often finds that a few classes have the same properties that can be
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000445shared, but a class with these properties does not have enough state to create
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000446an object from. A sub-class must extend the abstract class and add the
447missing state and/or methods before it can be used to create objects for.
448
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000449For example, a Shape class could store a color and thickness. You cannot
450create a Shape object, it is missing the information about what kind of shape
451it is. The Shape class functions as the base for a Square and a Triangle
452class, for which objects can be created. Example: >
453
454 abstract class Shape
Doug Kearns74da0ee2023-12-14 20:26:26 +0100455 var color = Color.Black
456 var thickness = 10
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000457 endclass
458
459 class Square extends Shape
Doug Kearns74da0ee2023-12-14 20:26:26 +0100460 var size: number
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000461
462 def new(this.size)
463 enddef
464 endclass
465
466 class Triangle extends Shape
Doug Kearns74da0ee2023-12-14 20:26:26 +0100467 var base: number
468 var height: number
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000469
470 def new(this.base, this.height)
471 enddef
472 endclass
473<
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000474An abstract class is defined the same way as a normal class, except that it
475does not have any new() method. *E1359*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000476
h_east596a9f22023-11-21 21:24:23 +0900477 *abstract-method* *E1371* *E1372*
Yegappan Lakshmanan7bcd25c2023-09-08 19:27:51 +0200478An abstract method can be defined in an abstract class by using the "abstract"
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700479prefix when defining the method: >
Yegappan Lakshmanan7bcd25c2023-09-08 19:27:51 +0200480
481 abstract class Shape
482 abstract def Draw()
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200483 abstract static def SetColor()
Yegappan Lakshmanan7bcd25c2023-09-08 19:27:51 +0200484 endclass
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200485<
Yegappan Lakshmananef9e3f82023-11-02 20:43:57 +0100486A static method in an abstract class cannot be an abstract method.
487
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200488 *E1373*
Yegappan Lakshmanan7bcd25c2023-09-08 19:27:51 +0200489A class extending the abstract class must implement all the abstract methods.
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200490The signature (arguments, argument types and return type) must be exactly the
Yegappan Lakshmanan26e8f7b2023-10-06 10:24:10 -0700491same. If the return type of a method is a class, then that class or one of
492its subclasses can be used in the extended method. Class methods in an
493abstract class can also be abstract methods.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000494
495==============================================================================
496
Bram Moolenaarbe4e0162023-02-02 13:59:48 +00004975. Using an interface *Vim9-using-interface*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000498
499The example above with Shape, Square and Triangle can be made more useful if
500we add a method to compute the surface of the object. For that we create the
501interface called HasSurface, which specifies one method Surface() that returns
502a number. This example extends the one above: >
503
504 abstract class Shape
Doug Kearns74da0ee2023-12-14 20:26:26 +0100505 var color = Color.Black
506 var thickness = 10
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000507 endclass
508
509 interface HasSurface
510 def Surface(): number
511 endinterface
512
513 class Square extends Shape implements HasSurface
Doug Kearns74da0ee2023-12-14 20:26:26 +0100514 var size: number
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000515
516 def new(this.size)
517 enddef
518
519 def Surface(): number
520 return this.size * this.size
521 enddef
522 endclass
523
524 class Triangle extends Shape implements HasSurface
Doug Kearns74da0ee2023-12-14 20:26:26 +0100525 var base: number
526 var height: number
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000527
528 def new(this.base, this.height)
529 enddef
530
531 def Surface(): number
532 return this.base * this.height / 2
533 enddef
534 endclass
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200535<
536 *E1348* *E1349* *E1367* *E1382* *E1383*
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000537If a class declares to implement an interface, all the items specified in the
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200538interface must appear in the class, with the same types.
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000539
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000540The interface name can be used as a type: >
541
542 var shapes: list<HasSurface> = [
543 Square.new(12),
544 Triangle.new(8, 15),
545 ]
546 for shape in shapes
547 echo $'the surface is {shape.Surface()}'
548 endfor
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200549<
Yegappan Lakshmanan2dede3d2023-09-27 19:02:01 +0200550 *E1378* *E1379* *E1380* *E1387*
551An interface can contain only object methods and read-only object variables.
Ernie Rael03042a22023-11-11 08:53:32 +0100552An interface cannot contain read-write or protected object variables,
553protected object methods, class variables and class methods.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000554
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200555An interface can extend another interface using "extends". The sub-interface
556inherits all the instance variables and methods from the super interface.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000557
558==============================================================================
559
Bram Moolenaarbe4e0162023-02-02 13:59:48 +00005606. More class details *Vim9-class* *Class* *class*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000561
562Defining a class ~
563 *:class* *:endclass* *:abstract*
564A class is defined between `:class` and `:endclass`. The whole class is
565defined in one script file. It is not possible to add to a class later.
566
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000567A class can only be defined in a |Vim9| script file. *E1316*
Bram Moolenaar00b28d62022-12-08 15:32:33 +0000568A class cannot be defined inside a function.
569
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000570It is possible to define more than one class in a script file. Although it
571usually is better to export only one main class. It can be useful to define
572types, enums and helper classes though.
573
574The `:abstract` keyword may be prefixed and `:export` may be used. That gives
575these variants: >
576
577 class ClassName
578 endclass
579
580 export class ClassName
581 endclass
582
583 abstract class ClassName
584 endclass
585
586 export abstract class ClassName
587 endclass
588<
589 *E1314*
590The class name should be CamelCased. It must start with an uppercase letter.
591That avoids clashing with builtin types.
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000592 *E1315*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000593After the class name these optional items can be used. Each can appear only
594once. They can appear in any order, although this order is recommended: >
595 extends ClassName
596 implements InterfaceName, OtherInterface
597 specifies SomeInterface
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200598< *E1355* *E1369*
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700599Each variable and method name can be used only once. It is not possible to
600define a method with the same name and different type of arguments. It is not
Ernie Rael03042a22023-11-11 08:53:32 +0100601possible to use a public and protected member variable with the same name. A
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700602object variable name used in a super class cannot be reused in a child class.
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000603
604
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700605Object Variable Initialization ~
Ernie Rael03042a22023-11-11 08:53:32 +0100606
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700607If the type of a variable is not explicitly specified in a class, then it is
608set to "any" during class definition. When an object is instantiated from the
609class, then the type of the variable is set.
Yegappan Lakshmanan618e47d2023-08-22 21:29:28 +0200610
Yegappan Lakshmananf3b68d42023-09-29 22:50:02 +0200611The following reserved keyword names cannot be used as an object or class
612variable name: "super", "this", "true", "false", "null", "null_blob",
613"null_dict", "null_function", "null_list", "null_partial", "null_string",
614"null_channel" and "null_job".
Yegappan Lakshmanan618e47d2023-08-22 21:29:28 +0200615
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000616Extending a class ~
617 *extends*
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000618A class can extend one other class. *E1352* *E1353* *E1354*
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000619The basic idea is to build on top of an existing class, add properties to it.
620
621The extended class is called the "base class" or "super class". The new class
622is called the "child class".
623
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700624Object variables from the base class are all taken over by the child class. It
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000625is not possible to override them (unlike some other languages).
626
627 *E1356* *E1357* *E1358*
Yegappan Lakshmananb32064f2023-10-02 21:43:58 +0200628Object methods of the base class can be overruled. The signature (arguments,
Yegappan Lakshmanan26e8f7b2023-10-06 10:24:10 -0700629argument types and return type) must be exactly the same. If the return type
630of a method is a class, then that class or one of its subclasses can be used
631in the extended method. The method of the base class can be called by
632prefixing "super.".
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000633
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200634 *E1377*
Ernie Rael03042a22023-11-11 08:53:32 +0100635The access level of a method (public or protected) in a child class should be
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200636the same as the super class.
637
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000638Other object methods of the base class are taken over by the child class.
639
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700640Class methods, including methods starting with "new", can be overruled, like
641with object methods. The method on the base class can be called by prefixing
642the name of the class (for class methods) or "super.".
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000643
644Unlike other languages, the constructor of the base class does not need to be
645invoked. In fact, it cannot be invoked. If some initialization from the base
646class also needs to be done in a child class, put it in an object method and
647call that method from every constructor().
648
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700649If the base class did not specify a new() method then one was automatically
650created. This method will not be taken over by the child class. The child
651class can define its own new() method, or, if there isn't one, a new() method
652will be added automatically.
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000653
654
655A class implementing an interface ~
Yegappan Lakshmanan2dede3d2023-09-27 19:02:01 +0200656 *implements* *E1346* *E1347* *E1389*
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000657A class can implement one or more interfaces. The "implements" keyword can
658only appear once *E1350* . Multiple interfaces can be specified, separated by
659commas. Each interface name can appear only once. *E1351*
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000660
661
662A class defining an interface ~
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000663 *specifies*
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700664A class can declare its interface, the object variables and methods, with a
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000665named interface. This avoids the need for separately specifying the
Bram Moolenaar00b28d62022-12-08 15:32:33 +0000666interface, which is often done in many languages, especially Java.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000667
668
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000669Items in a class ~
Yegappan Lakshmanan2dede3d2023-09-27 19:02:01 +0200670 *E1318* *E1325* *E1388*
Bram Moolenaardd60c362023-02-27 15:49:53 +0000671Inside a class, in between `:class` and `:endclass`, these items can appear:
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700672- An object variable declaration: >
Doug Kearns74da0ee2023-12-14 20:26:26 +0100673 var _protectedVariableName: memberType
674 var readonlyVariableName: memberType
675 public var readwriteVariableName: memberType
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700676- A class variable declaration: >
Doug Kearns74da0ee2023-12-14 20:26:26 +0100677 static var _protectedClassVariableName: memberType
678 static var readonlyClassVariableName: memberType
679 static var public readwriteClassVariableName: memberType
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000680- A constructor method: >
Bram Moolenaar938ae282023-02-20 20:44:55 +0000681 def new(arguments)
682 def newName(arguments)
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200683- A class method: >
684 static def SomeMethod(arguments)
Ernie Rael03042a22023-11-11 08:53:32 +0100685 static def _ProtectedMethod(arguments)
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000686- An object method: >
Bram Moolenaar938ae282023-02-20 20:44:55 +0000687 def SomeMethod(arguments)
Ernie Rael03042a22023-11-11 08:53:32 +0100688 def _ProtectedMethod(arguments)
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200689
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700690For the object variable the type must be specified. The best way is to do
691this explicitly with ": {type}". For simple types you can also use an
692initializer, such as "= 123", and Vim will see that the type is a number.
693Avoid doing this for more complex types and when the type will be incomplete.
694For example: >
Doug Kearns74da0ee2023-12-14 20:26:26 +0100695 var nameList = []
Bram Moolenaarf1dcd142022-12-31 15:30:45 +0000696This specifies a list, but the item type is unknown. Better use: >
Doug Kearns74da0ee2023-12-14 20:26:26 +0100697 var nameList: list<string>
Bram Moolenaarf1dcd142022-12-31 15:30:45 +0000698The initialization isn't needed, the list is empty by default.
699 *E1330*
700Some types cannot be used, such as "void", "null" and "v:none".
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000701
702
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000703Defining an interface ~
704 *:interface* *:endinterface*
705An interface is defined between `:interface` and `:endinterface`. It may be
706prefixed with `:export`: >
707
708 interface InterfaceName
709 endinterface
710
711 export interface InterfaceName
712 endinterface
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000713< *E1344*
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700714An interface can declare object variables, just like in a class but without
715any initializer.
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000716 *E1345*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000717An interface can declare methods with `:def`, including the arguments and
718return type, but without the body and without `:enddef`. Example: >
719
720 interface HasSurface
Doug Kearns74da0ee2023-12-14 20:26:26 +0100721 var size: number
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000722 def Surface(): number
723 endinterface
724
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000725An interface name must start with an uppercase letter. *E1343*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000726The "Has" prefix can be used to make it easier to guess this is an interface
727name, with a hint about what it provides.
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000728An interface can only be defined in a |Vim9| script file. *E1342*
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200729An interface cannot "implement" another interface but it can "extend" another
730interface. *E1381*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000731
732
Bram Moolenaar938ae282023-02-20 20:44:55 +0000733null object ~
734
Bram Moolenaardd60c362023-02-27 15:49:53 +0000735When a variable is declared to have the type of an object, but it is not
Bram Moolenaar938ae282023-02-20 20:44:55 +0000736initialized, the value is null. When trying to use this null object Vim often
737does not know what class was supposed to be used. Vim then cannot check if
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700738a variable name is correct and you will get an "Using a null object" error,
h_eastba77bbb2023-10-03 04:47:13 +0900739even when the variable name is invalid. *E1360* *E1362*
Bram Moolenaar938ae282023-02-20 20:44:55 +0000740
741
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000742Default constructor ~
Yegappan Lakshmanan413f8392023-09-28 22:46:37 +0200743 *default-constructor*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000744In case you define a class without a new() method, one will be automatically
745defined. This default constructor will have arguments for all the object
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700746variables, in the order they were specified. Thus if your class looks like: >
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000747
748 class AutoNew
Doug Kearns74da0ee2023-12-14 20:26:26 +0100749 var name: string
750 var age: number
751 var gender: Gender
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000752 endclass
753
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700754Then the default constructor will be: >
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000755
Bram Moolenaar65b0d162022-12-13 18:43:22 +0000756 def new(this.name = v:none, this.age = v:none, this.gender = v:none)
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000757 enddef
758
Bram Moolenaar65b0d162022-12-13 18:43:22 +0000759The "= v:none" default values make the arguments optional. Thus you can also
760call `new()` without any arguments. No assignment will happen and the default
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700761value for the object variables will be used. This is a more useful example,
Bram Moolenaar65b0d162022-12-13 18:43:22 +0000762with default values: >
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000763
764 class TextPosition
Doug Kearns74da0ee2023-12-14 20:26:26 +0100765 var lnum: number = 1
766 var col: number = 1
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000767 endclass
768
769If you want the constructor to have mandatory arguments, you need to write it
770yourself. For example, if for the AutoNew class above you insist on getting
771the name, you can define the constructor like this: >
772
Bram Moolenaar65b0d162022-12-13 18:43:22 +0000773 def new(this.name, this.age = v:none, this.gender = v:none)
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000774 enddef
Yegappan Lakshmanan563e6442023-12-05 08:19:06 -0800775<
776When using the default new() method, if the order of the object variables in
777the class is changed later, then all the callers of the default new() method
778needs to change. To avoid this, the new() method can be explicitly defined
779without any arguments.
780
781 *E1328*
Bram Moolenaar65b0d162022-12-13 18:43:22 +0000782Note that you cannot use another default value than "v:none" here. If you
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700783want to initialize the object variables, do it where they are declared. This
Bram Moolenaar65b0d162022-12-13 18:43:22 +0000784way you only need to look in one place for the default values.
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000785
Ernie Rael03042a22023-11-11 08:53:32 +0100786All object variables will be used in the default constructor, including
787protected access ones.
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000788
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700789If the class extends another one, the object variables of that class will come
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000790first.
791
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000792
793Multiple constructors ~
794
795Normally a class has just one new() constructor. In case you find that the
796constructor is often called with the same arguments you may want to simplify
797your code by putting those arguments into a second constructor method. For
798example, if you tend to use the color black a lot: >
799
800 def new(this.garment, this.color, this.size)
801 enddef
802 ...
803 var pants = new(Garment.pants, Color.black, "XL")
804 var shirt = new(Garment.shirt, Color.black, "XL")
805 var shoes = new(Garment.shoes, Color.black, "45")
806
807Instead of repeating the color every time you can add a constructor that
808includes it: >
809
810 def newBlack(this.garment, this.size)
811 this.color = Color.black
812 enddef
813 ...
814 var pants = newBlack(Garment.pants, "XL")
815 var shirt = newBlack(Garment.shirt, "XL")
816 var shoes = newBlack(Garment.shoes, "9.5")
817
818Note that the method name must start with "new". If there is no method called
819"new()" then the default constructor is added, even though there are other
820constructor methods.
821
822
823==============================================================================
824
Bram Moolenaarbe4e0162023-02-02 13:59:48 +00008257. Type definition *Vim9-type* *:type*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000826
Yegappan Lakshmanan2a71b542023-12-14 20:03:03 +0100827 *E1393* *E1395* *E1396* *E1397* *E1398*
828A type definition is giving a name to a type specification. This is also
829known as a "type alias". The type alias can be used wherever a built-in type
830can be used. Example: >
Yegappan Lakshmanan26e8f7b2023-10-06 10:24:10 -0700831
Yegappan Lakshmanan2a71b542023-12-14 20:03:03 +0100832 type ListOfStrings = list<string>
833 var s: ListOfStrings = ['a', 'b']
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000834
Yegappan Lakshmanan2a71b542023-12-14 20:03:03 +0100835 def ProcessStr(str: ListOfStrings): ListOfStrings
836 return str
837 enddef
838 echo ProcessStr(s)
839<
840 *E1394*
841A type alias name must start with an upper case character. Only existing
842types can be aliased.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000843
Yegappan Lakshmanan2a71b542023-12-14 20:03:03 +0100844 *E1399*
845A type alias can be created only at the script level and not inside a
846function. A type alias can be exported and used across scripts.
847
848 *E1400* *E1401* *E1402* *E1403* *E1407*
849A type alias cannot be used as an expression. A type alias cannot be used in
850the left-hand-side of an assignment.
851
852For a type alias name, the |typename()| function returns the type that is
853aliased: >
854
855 type ListOfStudents = list<dict<any>>
856 echo typename(ListOfStudents)
857 typealias<list<dict<any>>>
858<
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000859==============================================================================
860
Bram Moolenaarbe4e0162023-02-02 13:59:48 +00008618. Enum *Vim9-enum* *:enum* *:endenum*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000862
Yegappan Lakshmanan26e8f7b2023-10-06 10:24:10 -0700863{not implemented yet}
864
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000865An enum is a type that can have one of a list of values. Example: >
866
867 :enum Color
868 White
869 Red
870 Green
871 Blue
872 Black
873 :endenum
874
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000875
876==============================================================================
877
8789. Rationale
879
880Most of the choices for |Vim9| classes come from popular and recently
881developed languages, such as Java, TypeScript and Dart. The syntax has been
882made to fit with the way Vim script works, such as using `endclass` instead of
883using curly braces around the whole class.
884
885Some common constructs of object-oriented languages were chosen very long ago
886when this kind of programming was still new, and later found to be
887sub-optimal. By this time those constructs were widely used and changing them
888was not an option. In Vim we do have the freedom to make different choices,
889since classes are completely new. We can make the syntax simpler and more
890consistent than what "old" languages use. Without diverting too much, it
891should still mostly look like what you know from existing languages.
892
893Some recently developed languages add all kinds of fancy features that we
894don't need for Vim. But some have nice ideas that we do want to use.
895Thus we end up with a base of what is common in popular languages, dropping
896what looks like a bad idea, and adding some nice features that are easy to
897understand.
898
899The main rules we use to make decisions:
900- Keep it simple.
901- No surprises, mostly do what other languages are doing.
902- Avoid mistakes from the past.
903- Avoid the need for the script writer to consult the help to understand how
904 things work, most things should be obvious.
905- Keep it consistent.
906- Aim at an average size plugin, not at a huge project.
907
908
909Using new() for the constructor ~
910
911Many languages use the class name for the constructor method. A disadvantage
912is that quite often this is a long name. And when changing the class name all
913constructor methods need to be renamed. Not a big deal, but still a
914disadvantage.
915
916Other languages, such as TypeScript, use a specific name, such as
917"constructor()". That seems better. However, using "new" or "new()" to
918create a new object has no obvious relation with "constructor()".
919
920For |Vim9| script using the same method name for all constructors seemed like
921the right choice, and by calling it new() the relation between the caller and
922the method being called is obvious.
923
924
925No overloading of the constructor ~
926
927In Vim script, both legacy and |Vim9| script, there is no overloading of
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700928methods. That means it is not possible to use the same method name with
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000929different types of arguments. Therefore there also is only one new()
930constructor.
931
932With |Vim9| script it would be possible to support overloading, since
933arguments are typed. However, this gets complicated very quickly. Looking at
934a new() call one has to inspect the types of the arguments to know which of
935several new() methods is actually being called. And that can require
936inspecting quite a bit of code. For example, if one of the arguments is the
937return value of a method, you need to find that method to see what type it is
938returning.
939
940Instead, every constructor has to have a different name, starting with "new".
941That way multiple constructors with different arguments are possible, while it
942is very easy to see which constructor is being used. And the type of
943arguments can be properly checked.
944
945
946No overloading of methods ~
947
948Same reasoning as for the constructor: It is often not obvious what type
949arguments have, which would make it difficult to figure out what method is
950actually being called. Better just give the methods a different name, then
951type checking will make sure it works as you intended. This rules out
952polymorphism, which we don't really need anyway.
953
954
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000955Single inheritance and interfaces ~
956
957Some languages support multiple inheritance. Although that can be useful in
958some cases, it makes the rules of how a class works quite complicated.
959Instead, using interfaces to declare what is supported is much simpler. The
960very popular Java language does it this way, and it should be good enough for
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000961Vim. The "keep it simple" rule applies here.
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000962
963Explicitly declaring that a class supports an interface makes it easy to see
964what a class is intended for. It also makes it possible to do proper type
965checking. When an interface is changed any class that declares to implement
966it will be checked if that change was also changed. The mechanism to assume a
967class implements an interface just because the methods happen to match is
968brittle and leads to obscure problems, let's not do that.
969
970
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700971Using "this.variable" everywhere ~
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000972
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700973The object variables in various programming languages can often be accessed in
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000974different ways, depending on the location. Sometimes "this." has to be
975prepended to avoid ambiguity. They are usually declared without "this.".
976That is quite inconsistent and sometimes confusing.
977
978A very common issue is that in the constructor the arguments use the same name
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700979as the object variable. Then for these variables "this." needs to be prefixed
980in the body, while for other variables this is not needed and often omitted.
981This leads to a mix of variables with and without "this.", which is
982inconsistent.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000983
984For |Vim9| classes the "this." prefix is always used. Also for declaring the
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700985variables. Simple and consistent. When looking at the code inside a class
986it's also directly clear which variable references are object variables and
987which aren't.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000988
989
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700990Using class variables ~
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000991
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700992Using "static variable" to declare a class variable is very common, nothing
993new here. In |Vim9| script these can be accessed directly by their name.
994Very much like how a script-local variable can be used in a method. Since
995object variables are always accessed with "this." prepended, it's also quickly
996clear what kind of variable it is.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000997
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -0700998TypeScript prepends the class name before the class variable name, also inside
999the class. This has two problems: The class name can be rather long, taking
1000up quite a bit of space, and when the class is renamed all these places need
1001to be changed too.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +00001002
1003
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -07001004Declaring object and class variables ~
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +00001005
1006The main choice is whether to use "var" as with variable declarations.
1007TypeScript does not use it: >
1008 class Point {
1009 x: number;
1010 y = 0;
1011 }
1012
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -07001013Following that Vim object variables could be declared like this: >
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +00001014 class Point
1015 this.x: number
1016 this.y = 0
1017 endclass
1018
1019Some users pointed out that this looks more like an assignment than a
1020declaration. Adding "var" changes that: >
1021 class Point
Doug Kearns74da0ee2023-12-14 20:26:26 +01001022 var x: number
1023 var y = 0
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +00001024 endclass
1025
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -07001026We also need to be able to declare class variables using the "static" keyword.
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +00001027There we can also choose to leave out "var": >
1028 class Point
Doug Kearns74da0ee2023-12-14 20:26:26 +01001029 var x: number
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +00001030 static count = 0
1031 endclass
1032
1033Or do use it, before "static": >
1034 class Point
Doug Kearns74da0ee2023-12-14 20:26:26 +01001035 var x: number
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +00001036 var static count = 0
1037 endclass
1038
1039Or after "static": >
1040 class Point
Doug Kearns74da0ee2023-12-14 20:26:26 +01001041 var x: number
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +00001042 static var count = 0
1043 endclass
1044
1045This is more in line with "static def Func()".
1046
1047There is no clear preference whether to use "var" or not. The two main
1048reasons to leave it out are:
Doug Kearns74da0ee2023-12-14 20:26:26 +010010491. TypeScript and other popular languages do not use it.
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +000010502. Less clutter.
1051
Doug Kearns74da0ee2023-12-14 20:26:26 +01001052However, it is more common for languages to reuse their general variable and
1053function declaration syntax for class/object variables and methods. Vim9 also
1054reuses the general function declaration syntax for methods. So, for the sake
1055of consistency, we require "var" in these declarations.
1056
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +00001057
Bram Moolenaarc1c365c2022-12-04 20:13:24 +00001058Using "ClassName.new()" to construct an object ~
1059
1060Many languages use the "new" operator to create an object, which is actually
1061kind of strange, since the constructor is defined as a method with arguments,
1062not a command. TypeScript also has the "new" keyword, but the method is
1063called "constructor()", it is hard to see the relation between the two.
1064
1065In |Vim9| script the constructor method is called new(), and it is invoked as
1066new(), simple and straightforward. Other languages use "new ClassName()",
1067while there is no ClassName() method, it's a method by another name in the
1068class called ClassName. Quite confusing.
1069
1070
Ernie Rael03042a22023-11-11 08:53:32 +01001071Vim9class access modes ~
1072 *vim9-access-modes*
1073The variable access modes, and their meaning, supported by Vim9class are
1074 |public-variable| read and write from anywhere
1075 |read-only-variable| read from anywhere, write from inside the
1076 class and sub-classes
1077 |protected-variable| read and write from inside the class and
1078 sub-classes
1079
1080The method access modes are similar, but without the read-only mode.
1081
1082
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -07001083Default read access to object variables ~
Bram Moolenaarc1c365c2022-12-04 20:13:24 +00001084
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -07001085Some users will remark that the access rules for object variables are
Bram Moolenaarc1c365c2022-12-04 20:13:24 +00001086asymmetric. Well, that is intentional. Changing a value is a very different
1087action than reading a value. The read operation has no side effects, it can
1088be done any number of times without affecting the object. Changing the value
1089can have many side effects, and even have a ripple effect, affecting other
1090objects.
1091
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -07001092When adding object variables one usually doesn't think much about this, just
1093get the type right. And normally the values are set in the new() method.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +00001094Therefore defaulting to read access only "just works" in most cases. And when
1095directly writing you get an error, which makes you wonder if you actually want
1096to allow that. This helps writing code with fewer mistakes.
1097
1098
Ernie Rael03042a22023-11-11 08:53:32 +01001099Making object variables protected with an underscore ~
Bram Moolenaarc1c365c2022-12-04 20:13:24 +00001100
Ernie Rael03042a22023-11-11 08:53:32 +01001101When an object variable is protected, it can only be read and changed inside
1102the class (and in sub-classes), then it cannot be used outside of the class.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +00001103Prepending an underscore is a simple way to make that visible. Various
1104programming languages have this as a recommendation.
1105
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -07001106In case you change your mind and want to make the object variable accessible
Bram Moolenaarc1c365c2022-12-04 20:13:24 +00001107outside of the class, you will have to remove the underscore everywhere.
1108Since the name only appears in the class (and sub-classes) they will be easy
1109to find and change.
1110
1111The other way around is much harder: you can easily prepend an underscore to
Ernie Rael03042a22023-11-11 08:53:32 +01001112the object variable inside the class to make it protected, but any usage
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -07001113elsewhere you will have to track down and change. You may have to make it a
1114"set" method call. This reflects the real world problem that taking away
1115access requires work to be done for all places where that access exists.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +00001116
Ernie Rael03042a22023-11-11 08:53:32 +01001117An alternative would have been using the "protected" keyword, just like
1118"public" changes the access in the other direction. Well, that's just to
1119reduce the number of keywords.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +00001120
1121
Ernie Rael03042a22023-11-11 08:53:32 +01001122No private object variables ~
Bram Moolenaarc1c365c2022-12-04 20:13:24 +00001123
Yegappan Lakshmananc3b315f2023-09-24 14:36:17 -07001124Some languages provide several ways to control access to object variables.
1125The most known is "protected", and the meaning varies from language to
Ernie Rael03042a22023-11-11 08:53:32 +01001126language. Others are "shared", "private", "package" and even "friend".
Bram Moolenaarc1c365c2022-12-04 20:13:24 +00001127
1128These rules make life more difficult. That can be justified in projects where
1129many people work on the same, complex code where it is easy to make mistakes.
1130Especially when refactoring or other changes to the class model.
1131
1132The Vim scripts are expected to be used in a plugin, with just one person or a
1133small team working on it. Complex rules then only make it more complicated,
Bram Moolenaar71badf92023-04-22 22:40:14 +01001134the extra safety provided by the rules isn't really needed. Let's just keep
1135it simple and not specify access details.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +00001136
1137
1138==============================================================================
1139
114010. To be done later
1141
1142Can a newSomething() constructor invoke another constructor? If yes, what are
1143the restrictions?
1144
1145Thoughts:
1146- Generics for a class: `class <Tkey, Tentry>`
1147- Generics for a function: `def <Tkey> GetLast(key: Tkey)`
1148- Mixins: not sure if that is useful, leave out for simplicity.
1149
1150Some things that look like good additions:
1151- For testing: Mock mechanism
1152
1153An important class to be provided is "Promise". Since Vim is single
1154threaded, connecting asynchronous operations is a natural way of allowing
1155plugins to do their work without blocking the user. It's a uniform way to
1156invoke callbacks and handle timeouts and errors.
1157
1158
1159 vim:tw=78:ts=8:noet:ft=help:norl: