blob: c68288a0c5d5f9e6b6165ab93d4b5a48f88ea84e [file] [log] [blame]
Bram Moolenaar71badf92023-04-22 22:40:14 +01001*vim9class.txt* For Vim version 9.0. Last change: 2023 Mar 22
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|
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000143. Class members and functions |Vim9-class-member|
154. 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
31use this functionality effectively.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +000032
33The basic item is an object:
34- An object stores state. It contains one or more variables that can each
35 have a value.
Bram Moolenaarbe4e0162023-02-02 13:59:48 +000036- An object provides functions that use and manipulate its state. These
Bram Moolenaarc1c365c2022-12-04 20:13:24 +000037 functions are invoked "on the object", which is what sets it apart from the
38 traditional separation of data and code that manipulates the data.
39- An object has a well defined interface, with typed member variables and
40 member functions.
Bram Moolenaarbe4e0162023-02-02 13:59:48 +000041- Objects are created from a class and all objects have the same interface.
42 This does not change at runtime, it is not dynamic.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +000043
44An object can only be created by a class. A class provides:
45- A new() method, the constructor, which returns an object for the class.
46 This method is invoked on the class name: MyClass.new().
Bram Moolenaarbe4e0162023-02-02 13:59:48 +000047- State shared by all objects of the class: class variables (class members).
Bram Moolenaarc1c365c2022-12-04 20:13:24 +000048- A hierarchy of classes, with super-classes and sub-classes, inheritance.
49
50An interface is used to specify properties of an object:
51- An object can declare several interfaces that it implements.
52- Different objects implementing the same interface can be used the same way.
53
54The class hierarchy allows for single inheritance. Otherwise interfaces are
55to be used where needed.
56
57
58Class modeling ~
59
60You can model classes any way you like. Keep in mind what you are building,
61don't try to model the real world. This can be confusing, especially because
62teachers use real-world objects to explain class relations and you might think
63your model should therefore reflect the real world. It doesn't! The model
64should match your purpose.
65
Bram Moolenaarbe4e0162023-02-02 13:59:48 +000066Keep in mind that composition (an object contains other objects) is often
67better than inheritance (an object extends another object). Don't waste time
68trying to find the optimal class model. Or waste time discussing whether a
69square is a rectangle or that a rectangle is a square. It doesn't matter.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +000070
71
72==============================================================================
73
742. A simple class *Vim9-simple-class*
75
Bram Moolenaarbe4e0162023-02-02 13:59:48 +000076Let's start with a simple example: a class that stores a text position (see
77below for how to do this more efficiently): >
Bram Moolenaarc1c365c2022-12-04 20:13:24 +000078
79 class TextPosition
80 this.lnum: number
81 this.col: number
82
83 def new(lnum: number, col: number)
84 this.lnum = lnum
85 this.col = col
86 enddef
87
88 def SetLnum(lnum: number)
89 this.lnum = lnum
90 enddef
91
92 def SetCol(col: number)
93 this.col = col
94 enddef
95
96 def SetPosition(lnum: number, col: number)
97 this.lnum = lnum
98 this.col = col
99 enddef
100 endclass
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000101< *object* *Object*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000102You can create an object from this class with the new() method: >
103
104 var pos = TextPosition.new(1, 1)
105
106The object members "lnum" and "col" can be accessed directly: >
107
108 echo $'The text position is ({pos.lnum}, {pos.col})'
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000109< *E1317* *E1327*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000110If you have been using other object-oriented languages you will notice that
111in Vim the object members are consistently referred to with the "this."
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000112prefix. This is different from languages like Java and TypeScript. The
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000113naming convention makes the object members easy to spot. Also, when a
114variable does not have the "this." prefix you know it is not an object member.
115
116
117Member write access ~
118
119Now try to change an object member directly: >
120
121 pos.lnum = 9
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000122< *E1335*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000123This will give you an error! That is because by default object members can be
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000124read but not set. That's why the TextPosition class provides a method for it: >
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000125
126 pos.SetLnum(9)
127
128Allowing to read but not set an object member is the most common and safest
129way. Most often there is no problem using a value, while setting a value may
130have side effects that need to be taken care of. In this case, the SetLnum()
131method could check if the line number is valid and either give an error or use
132the closest valid value.
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000133 *:public* *E1331*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000134If you don't care about side effects and want to allow the object member to be
135changed at any time, you can make it public: >
136
137 public this.lnum: number
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000138 public this.col: number
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000139
140Now you don't need the SetLnum(), SetCol() and SetPosition() methods, setting
141"pos.lnum" directly above will no longer give an error.
Bram Moolenaarf1dcd142022-12-31 15:30:45 +0000142 *E1334*
143If you try to set an object member that doesn't exist you get an error: >
144 pos.other = 9
145< E1334: Object member not found: other ~
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000146
147
148Private members ~
Bram Moolenaarf1dcd142022-12-31 15:30:45 +0000149 *E1332* *E1333*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000150On the other hand, if you do not want the object members to be read directly,
151you can make them private. This is done by prefixing an underscore to the
152name: >
153
154 this._lnum: number
155 this._col number
156
157Now you need to provide methods to get the value of the private members.
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000158These are commonly called getters. We recommend using a name that starts with
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000159"Get": >
160
161 def GetLnum(): number
162 return this._lnum
163 enddef
164
165 def GetCol() number
166 return this._col
167 enddef
168
169This example isn't very useful, the members might as well have been public.
170It does become useful if you check the value. For example, restrict the line
171number to the total number of lines: >
172
173 def GetLnum(): number
174 if this._lnum > this._lineCount
175 return this._lineCount
176 endif
177 return this._lnum
178 enddef
179
180
181Simplifying the new() method ~
182
183Many constructors take values for the object members. Thus you very often see
184this pattern: >
185
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000186 class SomeClass
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000187 this.lnum: number
188 this.col: number
189
190 def new(lnum: number, col: number)
191 this.lnum = lnum
192 this.col = col
193 enddef
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000194 endclass
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000195
196Not only is this text you need to write, it also has the type of each member
197twice. Since this is so common a shorter way to write new() is provided: >
198
199 def new(this.lnum, this.col)
200 enddef
201
202The semantics are easy to understand: Providing the object member name,
203including "this.", as the argument to new() means the value provided in the
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000204new() call is assigned to that object member. This mechanism comes from the
205Dart language.
206
207Putting together this way of using new() and making the members public results
Bram Moolenaar71badf92023-04-22 22:40:14 +0100208in a much shorter class definition than what we started with: >
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000209
210 class TextPosition
211 public this.lnum: number
212 public this.col: number
213
214 def new(this.lnum, this.col)
215 enddef
216
217 def SetPosition(lnum: number, col: number)
218 this.lnum = lnum
219 this.col = col
220 enddef
221 endclass
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000222
223The sequence of constructing a new object is:
2241. Memory is allocated and cleared. All values are zero/false/empty.
2252. For each declared member that has an initializer, the expression is
226 evaluated and assigned to the member. This happens in the sequence the
227 members are declared in the class.
2283. Arguments in the new() method in the "this.name" form are assigned.
2294. The body of the new() method is executed.
230
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000231If the class extends a parent class, the same thing happens. In the second
232step the members of the parent class are done first. There is no need to call
233"super()" or "new()" on the parent.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000234
Yegappan Lakshmanan6ac15442023-08-20 18:20:17 +0200235When defining the new() method the return type should not be specified. It
236always returns an object of the class.
237
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000238==============================================================================
239
Bram Moolenaarbe4e0162023-02-02 13:59:48 +00002403. class members and functions *Vim9-class-member*
241
242 *:static* *E1337* *E1338*
243Class members are declared with "static". They are used by the name without a
244prefix: >
245
246 class OtherThing
247 this.size: number
248 static totalSize: number
249
250 def new(this.size)
251 totalSize += this.size
252 enddef
253 endclass
254< *E1340* *E1341*
255Since the name is used as-is, shadowing the name by a function argument name
256or local variable name is not allowed.
257
258Just like object members the access can be made private by using an underscore
259as the first character in the name, and it can be made public by prefixing
260"public": >
261
262 class OtherThing
263 static total: number # anybody can read, only class can write
264 static _sum: number # only class can read and write
265 public static result: number # anybody can read and write
266 endclass
267<
268 *class-function*
269Class functions are also declared with "static". They have no access to
270object members, they cannot use the "this" keyword. >
271
272 class OtherThing
273 this.size: number
274 static totalSize: number
275
276 # Clear the total size and return the value it had before.
277 static def ClearTotalSize(): number
278 var prev = totalSize
279 totalSize = 0
280 return prev
281 enddef
282 endclass
283
284Inside the class the function can be called by name directly, outside the
285class the class name must be prefixed: `OtherThing.ClearTotalSize()`.
286
287==============================================================================
288
2894. Using an abstract class *Vim9-abstract-class*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000290
291An abstract class forms the base for at least one sub-class. In the class
292model one often finds that a few classes have the same properties that can be
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000293shared, but a class with these properties does not have enough state to create
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000294an object from. A sub-class must extend the abstract class and add the
295missing state and/or methods before it can be used to create objects for.
296
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000297For example, a Shape class could store a color and thickness. You cannot
298create a Shape object, it is missing the information about what kind of shape
299it is. The Shape class functions as the base for a Square and a Triangle
300class, for which objects can be created. Example: >
301
302 abstract class Shape
303 this.color = Color.Black
304 this.thickness = 10
305 endclass
306
307 class Square extends Shape
308 this.size: number
309
310 def new(this.size)
311 enddef
312 endclass
313
314 class Triangle extends Shape
315 this.base: number
316 this.height: number
317
318 def new(this.base, this.height)
319 enddef
320 endclass
321<
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000322An abstract class is defined the same way as a normal class, except that it
323does not have any new() method. *E1359*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000324
325
326==============================================================================
327
Bram Moolenaarbe4e0162023-02-02 13:59:48 +00003285. Using an interface *Vim9-using-interface*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000329
330The example above with Shape, Square and Triangle can be made more useful if
331we add a method to compute the surface of the object. For that we create the
332interface called HasSurface, which specifies one method Surface() that returns
333a number. This example extends the one above: >
334
335 abstract class Shape
336 this.color = Color.Black
337 this.thickness = 10
338 endclass
339
340 interface HasSurface
341 def Surface(): number
342 endinterface
343
344 class Square extends Shape implements HasSurface
345 this.size: number
346
347 def new(this.size)
348 enddef
349
350 def Surface(): number
351 return this.size * this.size
352 enddef
353 endclass
354
355 class Triangle extends Shape implements HasSurface
356 this.base: number
357 this.height: number
358
359 def new(this.base, this.height)
360 enddef
361
362 def Surface(): number
363 return this.base * this.height / 2
364 enddef
365 endclass
366
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000367If a class declares to implement an interface, all the items specified in the
368interface must appear in the class, with the same types. *E1348* *E1349*
369
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000370The interface name can be used as a type: >
371
372 var shapes: list<HasSurface> = [
373 Square.new(12),
374 Triangle.new(8, 15),
375 ]
376 for shape in shapes
377 echo $'the surface is {shape.Surface()}'
378 endfor
379
380
381==============================================================================
382
Bram Moolenaarbe4e0162023-02-02 13:59:48 +00003836. More class details *Vim9-class* *Class* *class*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000384
385Defining a class ~
386 *:class* *:endclass* *:abstract*
387A class is defined between `:class` and `:endclass`. The whole class is
388defined in one script file. It is not possible to add to a class later.
389
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000390A class can only be defined in a |Vim9| script file. *E1316*
Bram Moolenaar00b28d62022-12-08 15:32:33 +0000391A class cannot be defined inside a function.
392
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000393It is possible to define more than one class in a script file. Although it
394usually is better to export only one main class. It can be useful to define
395types, enums and helper classes though.
396
397The `:abstract` keyword may be prefixed and `:export` may be used. That gives
398these variants: >
399
400 class ClassName
401 endclass
402
403 export class ClassName
404 endclass
405
406 abstract class ClassName
407 endclass
408
409 export abstract class ClassName
410 endclass
411<
412 *E1314*
413The class name should be CamelCased. It must start with an uppercase letter.
414That avoids clashing with builtin types.
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000415 *E1315*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000416After the class name these optional items can be used. Each can appear only
417once. They can appear in any order, although this order is recommended: >
418 extends ClassName
419 implements InterfaceName, OtherInterface
420 specifies SomeInterface
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000421< *E1355*
422Each member and function name can be used only once. It is not possible to
423define a function with the same name and different type of arguments.
424
425
Yegappan Lakshmanan618e47d2023-08-22 21:29:28 +0200426Member Initialization ~
427If the type of a member is not explicitly specified in a class, then it is set
428to "any" during class definition. When an object is instantiated from the
429class, then the type of the member is set.
430
431
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000432Extending a class ~
433 *extends*
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000434A class can extend one other class. *E1352* *E1353* *E1354*
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000435The basic idea is to build on top of an existing class, add properties to it.
436
437The extended class is called the "base class" or "super class". The new class
438is called the "child class".
439
440Object members from the base class are all taken over by the child class. It
441is not possible to override them (unlike some other languages).
442
443 *E1356* *E1357* *E1358*
444Object methods of the base class can be overruled. The signature (arguments,
445argument types and return type) must be exactly the same. The method of the
446base class can be called by prefixing "super.".
447
448Other object methods of the base class are taken over by the child class.
449
450Class functions, including functions starting with "new", can be overruled,
451like with object methods. The function on the base class can be called by
452prefixing the name of the class (for class functions) or "super.".
453
454Unlike other languages, the constructor of the base class does not need to be
455invoked. In fact, it cannot be invoked. If some initialization from the base
456class also needs to be done in a child class, put it in an object method and
457call that method from every constructor().
458
459If the base class did not specify a new() function then one was automatically
460created. This function will not be taken over by the child class. The child
461class can define its own new() function, or, if there isn't one, a new()
462function will be added automatically.
463
464
465A class implementing an interface ~
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000466 *implements* *E1346* *E1347*
467A class can implement one or more interfaces. The "implements" keyword can
468only appear once *E1350* . Multiple interfaces can be specified, separated by
469commas. Each interface name can appear only once. *E1351*
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000470
471
472A class defining an interface ~
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000473 *specifies*
Bram Moolenaar00b28d62022-12-08 15:32:33 +0000474A class can declare its interface, the object members and methods, with a
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000475named interface. This avoids the need for separately specifying the
Bram Moolenaar00b28d62022-12-08 15:32:33 +0000476interface, which is often done in many languages, especially Java.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000477
478
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000479Items in a class ~
480 *E1318* *E1325* *E1326*
Bram Moolenaardd60c362023-02-27 15:49:53 +0000481Inside a class, in between `:class` and `:endclass`, these items can appear:
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000482- An object member declaration: >
Bram Moolenaar938ae282023-02-20 20:44:55 +0000483 this._memberName: memberType
484 this.memberName: memberType
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000485 public this.memberName: memberType
486- A constructor method: >
Bram Moolenaar938ae282023-02-20 20:44:55 +0000487 def new(arguments)
488 def newName(arguments)
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000489- An object method: >
Bram Moolenaar938ae282023-02-20 20:44:55 +0000490 def SomeMethod(arguments)
Bram Moolenaarf1dcd142022-12-31 15:30:45 +0000491< *E1329*
492For the object member the type must be specified. The best way is to do this
493explicitly with ": {type}". For simple types you can also use an initializer,
494such as "= 123", and Vim will see that the type is a number. Avoid doing this
495for more complex types and when the type will be incomplete. For example: >
496 this.nameList = []
497This specifies a list, but the item type is unknown. Better use: >
498 this.nameList: list<string>
499The initialization isn't needed, the list is empty by default.
500 *E1330*
501Some types cannot be used, such as "void", "null" and "v:none".
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000502
503
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000504Defining an interface ~
505 *:interface* *:endinterface*
506An interface is defined between `:interface` and `:endinterface`. It may be
507prefixed with `:export`: >
508
509 interface InterfaceName
510 endinterface
511
512 export interface InterfaceName
513 endinterface
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000514< *E1344*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000515An interface can declare object members, just like in a class but without any
516initializer.
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000517 *E1345*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000518An interface can declare methods with `:def`, including the arguments and
519return type, but without the body and without `:enddef`. Example: >
520
521 interface HasSurface
522 this.size: number
523 def Surface(): number
524 endinterface
525
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000526An interface name must start with an uppercase letter. *E1343*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000527The "Has" prefix can be used to make it easier to guess this is an interface
528name, with a hint about what it provides.
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000529An interface can only be defined in a |Vim9| script file. *E1342*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000530
531
Bram Moolenaar938ae282023-02-20 20:44:55 +0000532null object ~
533
Bram Moolenaardd60c362023-02-27 15:49:53 +0000534When a variable is declared to have the type of an object, but it is not
Bram Moolenaar938ae282023-02-20 20:44:55 +0000535initialized, the value is null. When trying to use this null object Vim often
536does not know what class was supposed to be used. Vim then cannot check if
537a member name is correct and you will get an "Using a null object" error,
Bram Moolenaar71badf92023-04-22 22:40:14 +0100538even when the member name is invalid. *E1360* *E1362* *E1363*
Bram Moolenaar938ae282023-02-20 20:44:55 +0000539
540
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000541Default constructor ~
542
543In case you define a class without a new() method, one will be automatically
544defined. This default constructor will have arguments for all the object
545members, in the order they were specified. Thus if your class looks like: >
546
547 class AutoNew
548 this.name: string
549 this.age: number
550 this.gender: Gender
551 endclass
552
553Then The default constructor will be: >
554
Bram Moolenaar65b0d162022-12-13 18:43:22 +0000555 def new(this.name = v:none, this.age = v:none, this.gender = v:none)
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000556 enddef
557
Bram Moolenaar65b0d162022-12-13 18:43:22 +0000558The "= v:none" default values make the arguments optional. Thus you can also
559call `new()` without any arguments. No assignment will happen and the default
560value for the object members will be used. This is a more useful example,
561with default values: >
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000562
563 class TextPosition
564 this.lnum: number = 1
565 this.col: number = 1
566 endclass
567
568If you want the constructor to have mandatory arguments, you need to write it
569yourself. For example, if for the AutoNew class above you insist on getting
570the name, you can define the constructor like this: >
571
Bram Moolenaar65b0d162022-12-13 18:43:22 +0000572 def new(this.name, this.age = v:none, this.gender = v:none)
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000573 enddef
Bram Moolenaar65b0d162022-12-13 18:43:22 +0000574< *E1328*
575Note that you cannot use another default value than "v:none" here. If you
576want to initialize the object members, do it where they are declared. This
577way you only need to look in one place for the default values.
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000578
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000579All object members will be used in the default constructor, also private
580access ones.
581
582If the class extends another one, the object members of that class will come
583first.
584
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000585
586Multiple constructors ~
587
588Normally a class has just one new() constructor. In case you find that the
589constructor is often called with the same arguments you may want to simplify
590your code by putting those arguments into a second constructor method. For
591example, if you tend to use the color black a lot: >
592
593 def new(this.garment, this.color, this.size)
594 enddef
595 ...
596 var pants = new(Garment.pants, Color.black, "XL")
597 var shirt = new(Garment.shirt, Color.black, "XL")
598 var shoes = new(Garment.shoes, Color.black, "45")
599
600Instead of repeating the color every time you can add a constructor that
601includes it: >
602
603 def newBlack(this.garment, this.size)
604 this.color = Color.black
605 enddef
606 ...
607 var pants = newBlack(Garment.pants, "XL")
608 var shirt = newBlack(Garment.shirt, "XL")
609 var shoes = newBlack(Garment.shoes, "9.5")
610
611Note that the method name must start with "new". If there is no method called
612"new()" then the default constructor is added, even though there are other
613constructor methods.
614
615
616==============================================================================
617
Bram Moolenaarbe4e0162023-02-02 13:59:48 +00006187. Type definition *Vim9-type* *:type*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000619
620A type definition is giving a name to a type specification. For Example: >
621
622 :type ListOfStrings list<string>
623
624TODO: more explanation
625
626
627==============================================================================
628
Bram Moolenaarbe4e0162023-02-02 13:59:48 +00006298. Enum *Vim9-enum* *:enum* *:endenum*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000630
631An enum is a type that can have one of a list of values. Example: >
632
633 :enum Color
634 White
635 Red
636 Green
637 Blue
638 Black
639 :endenum
640
641TODO: more explanation
642
643
644==============================================================================
645
6469. Rationale
647
648Most of the choices for |Vim9| classes come from popular and recently
649developed languages, such as Java, TypeScript and Dart. The syntax has been
650made to fit with the way Vim script works, such as using `endclass` instead of
651using curly braces around the whole class.
652
653Some common constructs of object-oriented languages were chosen very long ago
654when this kind of programming was still new, and later found to be
655sub-optimal. By this time those constructs were widely used and changing them
656was not an option. In Vim we do have the freedom to make different choices,
657since classes are completely new. We can make the syntax simpler and more
658consistent than what "old" languages use. Without diverting too much, it
659should still mostly look like what you know from existing languages.
660
661Some recently developed languages add all kinds of fancy features that we
662don't need for Vim. But some have nice ideas that we do want to use.
663Thus we end up with a base of what is common in popular languages, dropping
664what looks like a bad idea, and adding some nice features that are easy to
665understand.
666
667The main rules we use to make decisions:
668- Keep it simple.
669- No surprises, mostly do what other languages are doing.
670- Avoid mistakes from the past.
671- Avoid the need for the script writer to consult the help to understand how
672 things work, most things should be obvious.
673- Keep it consistent.
674- Aim at an average size plugin, not at a huge project.
675
676
677Using new() for the constructor ~
678
679Many languages use the class name for the constructor method. A disadvantage
680is that quite often this is a long name. And when changing the class name all
681constructor methods need to be renamed. Not a big deal, but still a
682disadvantage.
683
684Other languages, such as TypeScript, use a specific name, such as
685"constructor()". That seems better. However, using "new" or "new()" to
686create a new object has no obvious relation with "constructor()".
687
688For |Vim9| script using the same method name for all constructors seemed like
689the right choice, and by calling it new() the relation between the caller and
690the method being called is obvious.
691
692
693No overloading of the constructor ~
694
695In Vim script, both legacy and |Vim9| script, there is no overloading of
696functions. That means it is not possible to use the same function name with
697different types of arguments. Therefore there also is only one new()
698constructor.
699
700With |Vim9| script it would be possible to support overloading, since
701arguments are typed. However, this gets complicated very quickly. Looking at
702a new() call one has to inspect the types of the arguments to know which of
703several new() methods is actually being called. And that can require
704inspecting quite a bit of code. For example, if one of the arguments is the
705return value of a method, you need to find that method to see what type it is
706returning.
707
708Instead, every constructor has to have a different name, starting with "new".
709That way multiple constructors with different arguments are possible, while it
710is very easy to see which constructor is being used. And the type of
711arguments can be properly checked.
712
713
714No overloading of methods ~
715
716Same reasoning as for the constructor: It is often not obvious what type
717arguments have, which would make it difficult to figure out what method is
718actually being called. Better just give the methods a different name, then
719type checking will make sure it works as you intended. This rules out
720polymorphism, which we don't really need anyway.
721
722
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000723Single inheritance and interfaces ~
724
725Some languages support multiple inheritance. Although that can be useful in
726some cases, it makes the rules of how a class works quite complicated.
727Instead, using interfaces to declare what is supported is much simpler. The
728very popular Java language does it this way, and it should be good enough for
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000729Vim. The "keep it simple" rule applies here.
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000730
731Explicitly declaring that a class supports an interface makes it easy to see
732what a class is intended for. It also makes it possible to do proper type
733checking. When an interface is changed any class that declares to implement
734it will be checked if that change was also changed. The mechanism to assume a
735class implements an interface just because the methods happen to match is
736brittle and leads to obscure problems, let's not do that.
737
738
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000739Using "this.member" everywhere ~
740
741The object members in various programming languages can often be accessed in
742different ways, depending on the location. Sometimes "this." has to be
743prepended to avoid ambiguity. They are usually declared without "this.".
744That is quite inconsistent and sometimes confusing.
745
746A very common issue is that in the constructor the arguments use the same name
747as the object member. Then for these members "this." needs to be prefixed in
748the body, while for other members this is not needed and often omitted. This
749leads to a mix of members with and without "this.", which is inconsistent.
750
751For |Vim9| classes the "this." prefix is always used. Also for declaring the
752members. Simple and consistent. When looking at the code inside a class it's
753also directly clear which variable references are object members and which
754aren't.
755
756
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000757Using class members ~
758
759Using "static member" to declare a class member is very common, nothing new
760here. In |Vim9| script these can be accessed directly by their name. Very
761much like how a script-local variable can be used in a function. Since object
762members are always accessed with "this." prepended, it's also quickly clear
763what kind of member it is.
764
765TypeScript prepends the class name before the class member, also inside the
766class. This has two problems: The class name can be rather long, taking up
767quite a bit of space, and when the class is renamed all these places need to
768be changed too.
769
770
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000771Declaring object and class members ~
772
773The main choice is whether to use "var" as with variable declarations.
774TypeScript does not use it: >
775 class Point {
776 x: number;
777 y = 0;
778 }
779
780Following that Vim object members could be declared like this: >
781 class Point
782 this.x: number
783 this.y = 0
784 endclass
785
786Some users pointed out that this looks more like an assignment than a
787declaration. Adding "var" changes that: >
788 class Point
789 var this.x: number
790 var this.y = 0
791 endclass
792
793We also need to be able to declare class members using the "static" keyword.
794There we can also choose to leave out "var": >
795 class Point
796 var this.x: number
797 static count = 0
798 endclass
799
800Or do use it, before "static": >
801 class Point
802 var this.x: number
803 var static count = 0
804 endclass
805
806Or after "static": >
807 class Point
808 var this.x: number
809 static var count = 0
810 endclass
811
812This is more in line with "static def Func()".
813
814There is no clear preference whether to use "var" or not. The two main
815reasons to leave it out are:
8161. TypeScript, Java and other popular languages do not use it.
8172. Less clutter.
818
819
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000820Using "ClassName.new()" to construct an object ~
821
822Many languages use the "new" operator to create an object, which is actually
823kind of strange, since the constructor is defined as a method with arguments,
824not a command. TypeScript also has the "new" keyword, but the method is
825called "constructor()", it is hard to see the relation between the two.
826
827In |Vim9| script the constructor method is called new(), and it is invoked as
828new(), simple and straightforward. Other languages use "new ClassName()",
829while there is no ClassName() method, it's a method by another name in the
830class called ClassName. Quite confusing.
831
832
833Default read access to object members ~
834
835Some users will remark that the access rules for object members are
836asymmetric. Well, that is intentional. Changing a value is a very different
837action than reading a value. The read operation has no side effects, it can
838be done any number of times without affecting the object. Changing the value
839can have many side effects, and even have a ripple effect, affecting other
840objects.
841
842When adding object members one usually doesn't think much about this, just get
843the type right. And normally the values are set in the new() method.
844Therefore defaulting to read access only "just works" in most cases. And when
845directly writing you get an error, which makes you wonder if you actually want
846to allow that. This helps writing code with fewer mistakes.
847
848
Bram Moolenaar00b28d62022-12-08 15:32:33 +0000849Making object members private with an underscore ~
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000850
851When an object member is private, it can only be read and changed inside the
852class (and in sub-classes), then it cannot be used outside of the class.
853Prepending an underscore is a simple way to make that visible. Various
854programming languages have this as a recommendation.
855
856In case you change your mind and want to make the object member accessible
857outside of the class, you will have to remove the underscore everywhere.
858Since the name only appears in the class (and sub-classes) they will be easy
859to find and change.
860
861The other way around is much harder: you can easily prepend an underscore to
862the object member inside the class to make it private, but any usage elsewhere
863you will have to track down and change. You may have to make it a "set"
864method call. This reflects the real world problem that taking away access
865requires work to be done for all places where that access exists.
866
867An alternative would have been using the "private" keyword, just like "public"
868changes the access in the other direction. Well, that's just to reduce the
869number of keywords.
870
871
872No protected object members ~
873
874Some languages provide several ways to control access to object members. The
875most known is "protected", and the meaning varies from language to language.
876Others are "shared", "private" and even "friend".
877
878These rules make life more difficult. That can be justified in projects where
879many people work on the same, complex code where it is easy to make mistakes.
880Especially when refactoring or other changes to the class model.
881
882The Vim scripts are expected to be used in a plugin, with just one person or a
883small team working on it. Complex rules then only make it more complicated,
Bram Moolenaar71badf92023-04-22 22:40:14 +0100884the extra safety provided by the rules isn't really needed. Let's just keep
885it simple and not specify access details.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000886
887
888==============================================================================
889
89010. To be done later
891
892Can a newSomething() constructor invoke another constructor? If yes, what are
893the restrictions?
894
895Thoughts:
896- Generics for a class: `class <Tkey, Tentry>`
897- Generics for a function: `def <Tkey> GetLast(key: Tkey)`
898- Mixins: not sure if that is useful, leave out for simplicity.
899
900Some things that look like good additions:
901- For testing: Mock mechanism
902
903An important class to be provided is "Promise". Since Vim is single
904threaded, connecting asynchronous operations is a natural way of allowing
905plugins to do their work without blocking the user. It's a uniform way to
906invoke callbacks and handle timeouts and errors.
907
908
909 vim:tw=78:ts=8:noet:ft=help:norl: