blob: c106bb60e75ca391d562a4834da69e3a240fc9bc [file] [log] [blame]
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +02001*vim9class.txt* For Vim version 9.0. Last change: 2023 Sep 18
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
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.
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200142 *E1326*
Bram Moolenaarf1dcd142022-12-31 15:30:45 +0000143If you try to set an object member that doesn't exist you get an error: >
144 pos.other = 9
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200145< E1326: Member not found on object "TextPosition": other ~
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000146
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200147 *E1376*
148A object member cannot be accessed using the class name.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000149
150Private members ~
Bram Moolenaarf1dcd142022-12-31 15:30:45 +0000151 *E1332* *E1333*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000152On the other hand, if you do not want the object members to be read directly,
153you can make them private. This is done by prefixing an underscore to the
154name: >
155
156 this._lnum: number
157 this._col number
158
159Now you need to provide methods to get the value of the private members.
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000160These are commonly called getters. We recommend using a name that starts with
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000161"Get": >
162
163 def GetLnum(): number
164 return this._lnum
165 enddef
166
167 def GetCol() number
168 return this._col
169 enddef
170
171This example isn't very useful, the members might as well have been public.
172It does become useful if you check the value. For example, restrict the line
173number to the total number of lines: >
174
175 def GetLnum(): number
176 if this._lnum > this._lineCount
177 return this._lineCount
178 endif
179 return this._lnum
180 enddef
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200181<
Yegappan Lakshmanancd7293b2023-08-27 19:18:23 +0200182Private methods ~
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200183 *E1366*
Yegappan Lakshmanancd7293b2023-08-27 19:18:23 +0200184If you want object methods to be accessible only from other methods of the
185same class and not used from outside the class, then you can make them
186private. This is done by prefixing the method name with an underscore: >
187
188 class SomeClass
189 def _Foo(): number
190 return 10
191 enddef
192 def Bar(): number
193 return this._Foo()
194 enddef
195 endclass
196<
197Accessing a private method outside the class will result in an error (using
198the above class): >
199
200 var a = SomeClass.new()
201 a._Foo()
202<
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000203Simplifying the new() method ~
204
205Many constructors take values for the object members. Thus you very often see
206this pattern: >
207
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000208 class SomeClass
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000209 this.lnum: number
210 this.col: number
211
212 def new(lnum: number, col: number)
213 this.lnum = lnum
214 this.col = col
215 enddef
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000216 endclass
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000217
218Not only is this text you need to write, it also has the type of each member
219twice. Since this is so common a shorter way to write new() is provided: >
220
221 def new(this.lnum, this.col)
222 enddef
223
224The semantics are easy to understand: Providing the object member name,
225including "this.", as the argument to new() means the value provided in the
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000226new() call is assigned to that object member. This mechanism comes from the
227Dart language.
228
229Putting together this way of using new() and making the members public results
Bram Moolenaar71badf92023-04-22 22:40:14 +0100230in a much shorter class definition than what we started with: >
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000231
232 class TextPosition
233 public this.lnum: number
234 public this.col: number
235
236 def new(this.lnum, this.col)
237 enddef
238
239 def SetPosition(lnum: number, col: number)
240 this.lnum = lnum
241 this.col = col
242 enddef
243 endclass
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000244
245The sequence of constructing a new object is:
2461. Memory is allocated and cleared. All values are zero/false/empty.
2472. For each declared member that has an initializer, the expression is
248 evaluated and assigned to the member. This happens in the sequence the
249 members are declared in the class.
2503. Arguments in the new() method in the "this.name" form are assigned.
2514. The body of the new() method is executed.
252
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000253If the class extends a parent class, the same thing happens. In the second
254step the members of the parent class are done first. There is no need to call
255"super()" or "new()" on the parent.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000256
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200257 *E1365*
Yegappan Lakshmanan6ac15442023-08-20 18:20:17 +0200258When defining the new() method the return type should not be specified. It
259always returns an object of the class.
260
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000261==============================================================================
262
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +02002633. Class Variables and Methods *Vim9-class-member*
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000264
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200265 *:static* *E1337* *E1338* *E1368*
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000266Class members are declared with "static". They are used by the name without a
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200267prefix in the class where they are defined: >
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000268
269 class OtherThing
270 this.size: number
271 static totalSize: number
272
273 def new(this.size)
274 totalSize += this.size
275 enddef
276 endclass
277< *E1340* *E1341*
278Since the name is used as-is, shadowing the name by a function argument name
279or local variable name is not allowed.
280
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200281 *E1374* *E1375*
282To access a class member outside of the class where it is defined, the class
283name prefix must be used. A class member cannot be accessed using an object.
284
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000285Just like object members the access can be made private by using an underscore
286as the first character in the name, and it can be made public by prefixing
287"public": >
288
289 class OtherThing
290 static total: number # anybody can read, only class can write
291 static _sum: number # only class can read and write
292 public static result: number # anybody can read and write
293 endclass
294<
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200295 *class-method*
296Class methods are also declared with "static". They can use the class
297variables but they have no access to the object variables, they cannot use the
298"this" keyword.
299>
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000300 class OtherThing
301 this.size: number
302 static totalSize: number
303
304 # Clear the total size and return the value it had before.
305 static def ClearTotalSize(): number
306 var prev = totalSize
307 totalSize = 0
308 return prev
309 enddef
310 endclass
311
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200312Inside the class the class method can be called by name directly, outside the
313class the class name must be prefixed: `OtherThing.ClearTotalSize()`. To use
314a super class method in a child class, the class name must be prefixed.
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000315
Yegappan Lakshmanancd7293b2023-08-27 19:18:23 +0200316Just like object methods the access can be made private by using an underscore
317as the first character in the method name: >
318
319 class OtherThing
320 static def _Foo()
321 echo "Foo"
322 enddef
323 def Bar()
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200324 _Foo()
Yegappan Lakshmanancd7293b2023-08-27 19:18:23 +0200325 enddef
326 endclass
Gianmaria Bajo4b9777a2023-08-29 22:26:30 +0200327<
328 *E1370*
329Note that constructors cannot be declared as "static", because they always
330are.
Yegappan Lakshmanancd7293b2023-08-27 19:18:23 +0200331
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200332To access the class methods and class variables of a super class in an
333extended class, the class name prefix should be used just as from anywhere
334outside of the defining class: >
335
336 vim9script
337 class Vehicle
338 static nextID: number = 1000
339 static def GetID(): number
340 nextID += 1
341 return nextID
342 enddef
343 endclass
344 class Car extends Vehicle
345 this.myID: number
346 def new()
347 this.myID = Vehicle.GetID()
348 enddef
349 endclass
350<
351Class variables and methods are not inherited by a child class. A child class
352can declare a static variable or a method with the same name as the one in the
353super class. Depending on the class where the member is used the
354corresponding class member will be used. The type of the class member in a
355child class can be different from that in the super class.
356
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000357==============================================================================
358
3594. Using an abstract class *Vim9-abstract-class*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000360
361An abstract class forms the base for at least one sub-class. In the class
362model one often finds that a few classes have the same properties that can be
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000363shared, but a class with these properties does not have enough state to create
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000364an object from. A sub-class must extend the abstract class and add the
365missing state and/or methods before it can be used to create objects for.
366
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000367For example, a Shape class could store a color and thickness. You cannot
368create a Shape object, it is missing the information about what kind of shape
369it is. The Shape class functions as the base for a Square and a Triangle
370class, for which objects can be created. Example: >
371
372 abstract class Shape
373 this.color = Color.Black
374 this.thickness = 10
375 endclass
376
377 class Square extends Shape
378 this.size: number
379
380 def new(this.size)
381 enddef
382 endclass
383
384 class Triangle extends Shape
385 this.base: number
386 this.height: number
387
388 def new(this.base, this.height)
389 enddef
390 endclass
391<
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000392An abstract class is defined the same way as a normal class, except that it
393does not have any new() method. *E1359*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000394
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200395 *abstract-method* *E1371* *E1372*
Yegappan Lakshmanan7bcd25c2023-09-08 19:27:51 +0200396An abstract method can be defined in an abstract class by using the "abstract"
397prefix when defining the function: >
398
399 abstract class Shape
400 abstract def Draw()
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200401 abstract static def SetColor()
Yegappan Lakshmanan7bcd25c2023-09-08 19:27:51 +0200402 endclass
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200403<
404 *E1373*
Yegappan Lakshmanan7bcd25c2023-09-08 19:27:51 +0200405A class extending the abstract class must implement all the abstract methods.
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200406The signature (arguments, argument types and return type) must be exactly the
407same. Class methods in an abstract class can also be abstract methods.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000408
409==============================================================================
410
Bram Moolenaarbe4e0162023-02-02 13:59:48 +00004115. Using an interface *Vim9-using-interface*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000412
413The example above with Shape, Square and Triangle can be made more useful if
414we add a method to compute the surface of the object. For that we create the
415interface called HasSurface, which specifies one method Surface() that returns
416a number. This example extends the one above: >
417
418 abstract class Shape
419 this.color = Color.Black
420 this.thickness = 10
421 endclass
422
423 interface HasSurface
424 def Surface(): number
425 endinterface
426
427 class Square extends Shape implements HasSurface
428 this.size: number
429
430 def new(this.size)
431 enddef
432
433 def Surface(): number
434 return this.size * this.size
435 enddef
436 endclass
437
438 class Triangle extends Shape implements HasSurface
439 this.base: number
440 this.height: number
441
442 def new(this.base, this.height)
443 enddef
444
445 def Surface(): number
446 return this.base * this.height / 2
447 enddef
448 endclass
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200449<
450 *E1348* *E1349* *E1367* *E1382* *E1383*
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000451If a class declares to implement an interface, all the items specified in the
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200452interface must appear in the class, with the same types.
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000453
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000454The interface name can be used as a type: >
455
456 var shapes: list<HasSurface> = [
457 Square.new(12),
458 Triangle.new(8, 15),
459 ]
460 for shape in shapes
461 echo $'the surface is {shape.Surface()}'
462 endfor
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200463<
464 *E1378* *E1379* *E1380*
465An interface can have only instance variables (read-only and read-write
466access) and methods. An interface cannot contain private variables, private
467methods, class variables and class methods.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000468
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200469An interface can extend another interface using "extends". The sub-interface
470inherits all the instance variables and methods from the super interface.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000471
472==============================================================================
473
Bram Moolenaarbe4e0162023-02-02 13:59:48 +00004746. More class details *Vim9-class* *Class* *class*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000475
476Defining a class ~
477 *:class* *:endclass* *:abstract*
478A class is defined between `:class` and `:endclass`. The whole class is
479defined in one script file. It is not possible to add to a class later.
480
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000481A class can only be defined in a |Vim9| script file. *E1316*
Bram Moolenaar00b28d62022-12-08 15:32:33 +0000482A class cannot be defined inside a function.
483
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000484It is possible to define more than one class in a script file. Although it
485usually is better to export only one main class. It can be useful to define
486types, enums and helper classes though.
487
488The `:abstract` keyword may be prefixed and `:export` may be used. That gives
489these variants: >
490
491 class ClassName
492 endclass
493
494 export class ClassName
495 endclass
496
497 abstract class ClassName
498 endclass
499
500 export abstract class ClassName
501 endclass
502<
503 *E1314*
504The class name should be CamelCased. It must start with an uppercase letter.
505That avoids clashing with builtin types.
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000506 *E1315*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000507After the class name these optional items can be used. Each can appear only
508once. They can appear in any order, although this order is recommended: >
509 extends ClassName
510 implements InterfaceName, OtherInterface
511 specifies SomeInterface
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200512< *E1355* *E1369*
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000513Each member and function name can be used only once. It is not possible to
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200514define a function with the same name and different type of arguments. It is
515not possible to use a public and private member variable with the same name.
516A object variable name used in a super class cannot be reused in a child
517class.
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000518
519
Yegappan Lakshmanan618e47d2023-08-22 21:29:28 +0200520Member Initialization ~
521If the type of a member is not explicitly specified in a class, then it is set
522to "any" during class definition. When an object is instantiated from the
523class, then the type of the member is set.
524
525
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000526Extending a class ~
527 *extends*
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000528A class can extend one other class. *E1352* *E1353* *E1354*
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000529The basic idea is to build on top of an existing class, add properties to it.
530
531The extended class is called the "base class" or "super class". The new class
532is called the "child class".
533
534Object members from the base class are all taken over by the child class. It
535is not possible to override them (unlike some other languages).
536
537 *E1356* *E1357* *E1358*
538Object methods of the base class can be overruled. The signature (arguments,
539argument types and return type) must be exactly the same. The method of the
540base class can be called by prefixing "super.".
541
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200542 *E1377*
543The access level of a method (public or private) in a child class should be
544the same as the super class.
545
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000546Other object methods of the base class are taken over by the child class.
547
548Class functions, including functions starting with "new", can be overruled,
549like with object methods. The function on the base class can be called by
550prefixing the name of the class (for class functions) or "super.".
551
552Unlike other languages, the constructor of the base class does not need to be
553invoked. In fact, it cannot be invoked. If some initialization from the base
554class also needs to be done in a child class, put it in an object method and
555call that method from every constructor().
556
557If the base class did not specify a new() function then one was automatically
558created. This function will not be taken over by the child class. The child
559class can define its own new() function, or, if there isn't one, a new()
560function will be added automatically.
561
562
563A class implementing an interface ~
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000564 *implements* *E1346* *E1347*
565A class can implement one or more interfaces. The "implements" keyword can
566only appear once *E1350* . Multiple interfaces can be specified, separated by
567commas. Each interface name can appear only once. *E1351*
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000568
569
570A class defining an interface ~
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000571 *specifies*
Bram Moolenaar00b28d62022-12-08 15:32:33 +0000572A class can declare its interface, the object members and methods, with a
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000573named interface. This avoids the need for separately specifying the
Bram Moolenaar00b28d62022-12-08 15:32:33 +0000574interface, which is often done in many languages, especially Java.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000575
576
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000577Items in a class ~
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200578 *E1318* *E1325*
Bram Moolenaardd60c362023-02-27 15:49:53 +0000579Inside a class, in between `:class` and `:endclass`, these items can appear:
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000580- An object member declaration: >
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200581 this._privateMemberName: memberType
582 this.readonlyMemberName: memberType
583 public this.readwriteMemberName: memberType
584- A class member declaration: >
585 static this._privateMemberName: memberType
586 static this.readonlyMemberName: memberType
587 static public this.readwriteMemberName: memberType
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000588- A constructor method: >
Bram Moolenaar938ae282023-02-20 20:44:55 +0000589 def new(arguments)
590 def newName(arguments)
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200591- A class method: >
592 static def SomeMethod(arguments)
593 static def _PrivateMethod(arguments)
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000594- An object method: >
Bram Moolenaar938ae282023-02-20 20:44:55 +0000595 def SomeMethod(arguments)
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200596 def _PrivateMethod(arguments)
597
Bram Moolenaarf1dcd142022-12-31 15:30:45 +0000598For the object member the type must be specified. The best way is to do this
599explicitly with ": {type}". For simple types you can also use an initializer,
600such as "= 123", and Vim will see that the type is a number. Avoid doing this
601for more complex types and when the type will be incomplete. For example: >
602 this.nameList = []
603This specifies a list, but the item type is unknown. Better use: >
604 this.nameList: list<string>
605The initialization isn't needed, the list is empty by default.
606 *E1330*
607Some types cannot be used, such as "void", "null" and "v:none".
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000608
609
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000610Defining an interface ~
611 *:interface* *:endinterface*
612An interface is defined between `:interface` and `:endinterface`. It may be
613prefixed with `:export`: >
614
615 interface InterfaceName
616 endinterface
617
618 export interface InterfaceName
619 endinterface
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000620< *E1344*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000621An interface can declare object members, just like in a class but without any
622initializer.
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000623 *E1345*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000624An interface can declare methods with `:def`, including the arguments and
625return type, but without the body and without `:enddef`. Example: >
626
627 interface HasSurface
628 this.size: number
629 def Surface(): number
630 endinterface
631
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000632An interface name must start with an uppercase letter. *E1343*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000633The "Has" prefix can be used to make it easier to guess this is an interface
634name, with a hint about what it provides.
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000635An interface can only be defined in a |Vim9| script file. *E1342*
Yegappan Lakshmanan00cd1822023-09-18 19:56:49 +0200636An interface cannot "implement" another interface but it can "extend" another
637interface. *E1381*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000638
639
Bram Moolenaar938ae282023-02-20 20:44:55 +0000640null object ~
641
Bram Moolenaardd60c362023-02-27 15:49:53 +0000642When a variable is declared to have the type of an object, but it is not
Bram Moolenaar938ae282023-02-20 20:44:55 +0000643initialized, the value is null. When trying to use this null object Vim often
644does not know what class was supposed to be used. Vim then cannot check if
645a member name is correct and you will get an "Using a null object" error,
Bram Moolenaar71badf92023-04-22 22:40:14 +0100646even when the member name is invalid. *E1360* *E1362* *E1363*
Bram Moolenaar938ae282023-02-20 20:44:55 +0000647
648
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000649Default constructor ~
650
651In case you define a class without a new() method, one will be automatically
652defined. This default constructor will have arguments for all the object
653members, in the order they were specified. Thus if your class looks like: >
654
655 class AutoNew
656 this.name: string
657 this.age: number
658 this.gender: Gender
659 endclass
660
661Then The default constructor will be: >
662
Bram Moolenaar65b0d162022-12-13 18:43:22 +0000663 def new(this.name = v:none, this.age = v:none, this.gender = v:none)
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000664 enddef
665
Bram Moolenaar65b0d162022-12-13 18:43:22 +0000666The "= v:none" default values make the arguments optional. Thus you can also
667call `new()` without any arguments. No assignment will happen and the default
668value for the object members will be used. This is a more useful example,
669with default values: >
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000670
671 class TextPosition
672 this.lnum: number = 1
673 this.col: number = 1
674 endclass
675
676If you want the constructor to have mandatory arguments, you need to write it
677yourself. For example, if for the AutoNew class above you insist on getting
678the name, you can define the constructor like this: >
679
Bram Moolenaar65b0d162022-12-13 18:43:22 +0000680 def new(this.name, this.age = v:none, this.gender = v:none)
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000681 enddef
Bram Moolenaar65b0d162022-12-13 18:43:22 +0000682< *E1328*
683Note that you cannot use another default value than "v:none" here. If you
684want to initialize the object members, do it where they are declared. This
685way you only need to look in one place for the default values.
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000686
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000687All object members will be used in the default constructor, also private
688access ones.
689
690If the class extends another one, the object members of that class will come
691first.
692
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000693
694Multiple constructors ~
695
696Normally a class has just one new() constructor. In case you find that the
697constructor is often called with the same arguments you may want to simplify
698your code by putting those arguments into a second constructor method. For
699example, if you tend to use the color black a lot: >
700
701 def new(this.garment, this.color, this.size)
702 enddef
703 ...
704 var pants = new(Garment.pants, Color.black, "XL")
705 var shirt = new(Garment.shirt, Color.black, "XL")
706 var shoes = new(Garment.shoes, Color.black, "45")
707
708Instead of repeating the color every time you can add a constructor that
709includes it: >
710
711 def newBlack(this.garment, this.size)
712 this.color = Color.black
713 enddef
714 ...
715 var pants = newBlack(Garment.pants, "XL")
716 var shirt = newBlack(Garment.shirt, "XL")
717 var shoes = newBlack(Garment.shoes, "9.5")
718
719Note that the method name must start with "new". If there is no method called
720"new()" then the default constructor is added, even though there are other
721constructor methods.
722
723
724==============================================================================
725
Bram Moolenaarbe4e0162023-02-02 13:59:48 +00007267. Type definition *Vim9-type* *:type*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000727
728A type definition is giving a name to a type specification. For Example: >
729
730 :type ListOfStrings list<string>
731
732TODO: more explanation
733
734
735==============================================================================
736
Bram Moolenaarbe4e0162023-02-02 13:59:48 +00007378. Enum *Vim9-enum* *:enum* *:endenum*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000738
739An enum is a type that can have one of a list of values. Example: >
740
741 :enum Color
742 White
743 Red
744 Green
745 Blue
746 Black
747 :endenum
748
749TODO: more explanation
750
751
752==============================================================================
753
7549. Rationale
755
756Most of the choices for |Vim9| classes come from popular and recently
757developed languages, such as Java, TypeScript and Dart. The syntax has been
758made to fit with the way Vim script works, such as using `endclass` instead of
759using curly braces around the whole class.
760
761Some common constructs of object-oriented languages were chosen very long ago
762when this kind of programming was still new, and later found to be
763sub-optimal. By this time those constructs were widely used and changing them
764was not an option. In Vim we do have the freedom to make different choices,
765since classes are completely new. We can make the syntax simpler and more
766consistent than what "old" languages use. Without diverting too much, it
767should still mostly look like what you know from existing languages.
768
769Some recently developed languages add all kinds of fancy features that we
770don't need for Vim. But some have nice ideas that we do want to use.
771Thus we end up with a base of what is common in popular languages, dropping
772what looks like a bad idea, and adding some nice features that are easy to
773understand.
774
775The main rules we use to make decisions:
776- Keep it simple.
777- No surprises, mostly do what other languages are doing.
778- Avoid mistakes from the past.
779- Avoid the need for the script writer to consult the help to understand how
780 things work, most things should be obvious.
781- Keep it consistent.
782- Aim at an average size plugin, not at a huge project.
783
784
785Using new() for the constructor ~
786
787Many languages use the class name for the constructor method. A disadvantage
788is that quite often this is a long name. And when changing the class name all
789constructor methods need to be renamed. Not a big deal, but still a
790disadvantage.
791
792Other languages, such as TypeScript, use a specific name, such as
793"constructor()". That seems better. However, using "new" or "new()" to
794create a new object has no obvious relation with "constructor()".
795
796For |Vim9| script using the same method name for all constructors seemed like
797the right choice, and by calling it new() the relation between the caller and
798the method being called is obvious.
799
800
801No overloading of the constructor ~
802
803In Vim script, both legacy and |Vim9| script, there is no overloading of
804functions. That means it is not possible to use the same function name with
805different types of arguments. Therefore there also is only one new()
806constructor.
807
808With |Vim9| script it would be possible to support overloading, since
809arguments are typed. However, this gets complicated very quickly. Looking at
810a new() call one has to inspect the types of the arguments to know which of
811several new() methods is actually being called. And that can require
812inspecting quite a bit of code. For example, if one of the arguments is the
813return value of a method, you need to find that method to see what type it is
814returning.
815
816Instead, every constructor has to have a different name, starting with "new".
817That way multiple constructors with different arguments are possible, while it
818is very easy to see which constructor is being used. And the type of
819arguments can be properly checked.
820
821
822No overloading of methods ~
823
824Same reasoning as for the constructor: It is often not obvious what type
825arguments have, which would make it difficult to figure out what method is
826actually being called. Better just give the methods a different name, then
827type checking will make sure it works as you intended. This rules out
828polymorphism, which we don't really need anyway.
829
830
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000831Single inheritance and interfaces ~
832
833Some languages support multiple inheritance. Although that can be useful in
834some cases, it makes the rules of how a class works quite complicated.
835Instead, using interfaces to declare what is supported is much simpler. The
836very popular Java language does it this way, and it should be good enough for
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000837Vim. The "keep it simple" rule applies here.
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000838
839Explicitly declaring that a class supports an interface makes it easy to see
840what a class is intended for. It also makes it possible to do proper type
841checking. When an interface is changed any class that declares to implement
842it will be checked if that change was also changed. The mechanism to assume a
843class implements an interface just because the methods happen to match is
844brittle and leads to obscure problems, let's not do that.
845
846
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000847Using "this.member" everywhere ~
848
849The object members in various programming languages can often be accessed in
850different ways, depending on the location. Sometimes "this." has to be
851prepended to avoid ambiguity. They are usually declared without "this.".
852That is quite inconsistent and sometimes confusing.
853
854A very common issue is that in the constructor the arguments use the same name
855as the object member. Then for these members "this." needs to be prefixed in
856the body, while for other members this is not needed and often omitted. This
857leads to a mix of members with and without "this.", which is inconsistent.
858
859For |Vim9| classes the "this." prefix is always used. Also for declaring the
860members. Simple and consistent. When looking at the code inside a class it's
861also directly clear which variable references are object members and which
862aren't.
863
864
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000865Using class members ~
866
867Using "static member" to declare a class member is very common, nothing new
868here. In |Vim9| script these can be accessed directly by their name. Very
869much like how a script-local variable can be used in a function. Since object
870members are always accessed with "this." prepended, it's also quickly clear
871what kind of member it is.
872
873TypeScript prepends the class name before the class member, also inside the
874class. This has two problems: The class name can be rather long, taking up
875quite a bit of space, and when the class is renamed all these places need to
876be changed too.
877
878
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000879Declaring object and class members ~
880
881The main choice is whether to use "var" as with variable declarations.
882TypeScript does not use it: >
883 class Point {
884 x: number;
885 y = 0;
886 }
887
888Following that Vim object members could be declared like this: >
889 class Point
890 this.x: number
891 this.y = 0
892 endclass
893
894Some users pointed out that this looks more like an assignment than a
895declaration. Adding "var" changes that: >
896 class Point
897 var this.x: number
898 var this.y = 0
899 endclass
900
901We also need to be able to declare class members using the "static" keyword.
902There we can also choose to leave out "var": >
903 class Point
904 var this.x: number
905 static count = 0
906 endclass
907
908Or do use it, before "static": >
909 class Point
910 var this.x: number
911 var static count = 0
912 endclass
913
914Or after "static": >
915 class Point
916 var this.x: number
917 static var count = 0
918 endclass
919
920This is more in line with "static def Func()".
921
922There is no clear preference whether to use "var" or not. The two main
923reasons to leave it out are:
9241. TypeScript, Java and other popular languages do not use it.
9252. Less clutter.
926
927
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000928Using "ClassName.new()" to construct an object ~
929
930Many languages use the "new" operator to create an object, which is actually
931kind of strange, since the constructor is defined as a method with arguments,
932not a command. TypeScript also has the "new" keyword, but the method is
933called "constructor()", it is hard to see the relation between the two.
934
935In |Vim9| script the constructor method is called new(), and it is invoked as
936new(), simple and straightforward. Other languages use "new ClassName()",
937while there is no ClassName() method, it's a method by another name in the
938class called ClassName. Quite confusing.
939
940
941Default read access to object members ~
942
943Some users will remark that the access rules for object members are
944asymmetric. Well, that is intentional. Changing a value is a very different
945action than reading a value. The read operation has no side effects, it can
946be done any number of times without affecting the object. Changing the value
947can have many side effects, and even have a ripple effect, affecting other
948objects.
949
950When adding object members one usually doesn't think much about this, just get
951the type right. And normally the values are set in the new() method.
952Therefore defaulting to read access only "just works" in most cases. And when
953directly writing you get an error, which makes you wonder if you actually want
954to allow that. This helps writing code with fewer mistakes.
955
956
Bram Moolenaar00b28d62022-12-08 15:32:33 +0000957Making object members private with an underscore ~
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000958
959When an object member is private, it can only be read and changed inside the
960class (and in sub-classes), then it cannot be used outside of the class.
961Prepending an underscore is a simple way to make that visible. Various
962programming languages have this as a recommendation.
963
964In case you change your mind and want to make the object member accessible
965outside of the class, you will have to remove the underscore everywhere.
966Since the name only appears in the class (and sub-classes) they will be easy
967to find and change.
968
969The other way around is much harder: you can easily prepend an underscore to
970the object member inside the class to make it private, but any usage elsewhere
971you will have to track down and change. You may have to make it a "set"
972method call. This reflects the real world problem that taking away access
973requires work to be done for all places where that access exists.
974
975An alternative would have been using the "private" keyword, just like "public"
976changes the access in the other direction. Well, that's just to reduce the
977number of keywords.
978
979
980No protected object members ~
981
982Some languages provide several ways to control access to object members. The
983most known is "protected", and the meaning varies from language to language.
984Others are "shared", "private" and even "friend".
985
986These rules make life more difficult. That can be justified in projects where
987many people work on the same, complex code where it is easy to make mistakes.
988Especially when refactoring or other changes to the class model.
989
990The Vim scripts are expected to be used in a plugin, with just one person or a
991small team working on it. Complex rules then only make it more complicated,
Bram Moolenaar71badf92023-04-22 22:40:14 +0100992the extra safety provided by the rules isn't really needed. Let's just keep
993it simple and not specify access details.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000994
995
996==============================================================================
997
99810. To be done later
999
1000Can a newSomething() constructor invoke another constructor? If yes, what are
1001the restrictions?
1002
1003Thoughts:
1004- Generics for a class: `class <Tkey, Tentry>`
1005- Generics for a function: `def <Tkey> GetLast(key: Tkey)`
1006- Mixins: not sure if that is useful, leave out for simplicity.
1007
1008Some things that look like good additions:
1009- For testing: Mock mechanism
1010
1011An important class to be provided is "Promise". Since Vim is single
1012threaded, connecting asynchronous operations is a natural way of allowing
1013plugins to do their work without blocking the user. It's a uniform way to
1014invoke callbacks and handle timeouts and errors.
1015
1016
1017 vim:tw=78:ts=8:noet:ft=help:norl: