Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
literal-constructor.qdoc
Go to the documentation of this file.
1// Copyright (C) 2025 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
3
4/*!
5\page qmllint-warnings-and-errors-literal-constructor.html
6\ingroup qmllint-warnings-and-errors
7
8\title Literal constructor
9\brief [literal-constructor] Do not use function as a constructor.
10
11\qmllintwarningcategory literal-constructors
12
13\section1 Do not use function as a constructor
14
15\section2 What happened?
16A literal construction function was used as a constructor.
17
18\section2 Why is that bad?
19Calling a literal construction function such as \c{Number} as a regular
20function coerces the passed value to a primitive number. However, calling
21\c{Number} as a constructor returns an object deriving from \c {Number}
22containing that value. This is wasteful and likely not the expected outcome.
23Moreover, it may lead to unexpected or confusing behavior because of the
24returned value not being primitive.
25
26\section2 Example
27\qml
28import QtQuick
29
30Item {
31 function numberify(x) {
32 return new Number(x)
33 }
34 Component.onCompleted: {
35 let n = numberify("1")
36 console.log(typeof n) // object
37 console.log(n === 1) // false
38
39 if (new Boolean(false)) // All objects are truthy!
40 console.log("aaa") // aa
41 }
42}
43\endqml
44To fix this warning, do not call these functions as constructors but as regular
45functions:
46\qml
47import QtQuick
48
49Item {
50 function numberify(x) {
51 return Number(x)
52 }
53 Component.onCompleted: {
54 let n = numberify("1")
55 console.log(typeof n) // number
56 console.log(n === 1) // true
57
58 if (Boolean(false))
59 console.log("aaa") // <not executed>
60 }
61}
62\endqml
63
64\section1 Array has confusing semantics
65
66\section2 What happened?
67An \c Array constructor was used with more than one argument.
68
69\section2 Why is that bad?
70The \c{Array} constructor has confusing semantics:
71\list
72\li \c{new Array()} creates an empty array.
73\li \c{new Array(42)} creates an array with 42 elements.
74\li \c{new Array(42, 43)} creates an array with two elements, 42 and 43.
75\endlist
76
77\section2 Example
78\qml
79import QtQuick
80
81Item {
82 function createArray() {
83 return new Array(1, 2, 3)
84 }
85}
86\endqml
87
88To fix this warning, use \c{[...]} instead of \c{new Array(...)}.
89
90functions:
91\qml
92import QtQuick
93
94Item {
95 function createArray() {
96 return [1, 2, 3]
97 }
98}
99\endqml
100*/