In questa pagina

Costruttore letterale

Questa categoria di avviso viene indicata da qmllint come " [literal-constructors] ".

Non utilizzare una funzione come costruttore

Cosa è successo?

È stata utilizzata una funzione di costruzione letterale come costruttore.

Perché è un problema?

Chiamare una funzione di costruzione letterale come Number come una normale funzione converte il valore passato in un numero primitivo. Tuttavia, chiamare Number come costruttore restituisce un oggetto derivato da Number contenente quel valore. Ciò rappresenta uno spreco e probabilmente non è il risultato atteso. Inoltre, può portare a comportamenti imprevisti o confusi poiché il valore restituito non è primitivo.

Esempio

import QtQuick

Item {
    function numberify(x) {
        return new Number(x)
    }
    Component.onCompleted: {
        let n = numberify("1")
        console.log(typeof n)   // object
        console.log(n === 1)    // false

        if (new Boolean(false)) // All objects are truthy!
            console.log("aaa")  // aa
    }
}

Per risolvere questo avviso, non chiamare queste funzioni come costruttori ma come normali funzioni:

import QtQuick

Item {
    function numberify(x) {
        return Number(x)
    }
    Component.onCompleted: {
        let n = numberify("1")
        console.log(typeof n)   // number
        console.log(n === 1)    // true

        if (Boolean(false))
            console.log("aaa")  // <not executed>
    }
}

L'array presenta una semantica ambigua

Cosa è successo?

È stato utilizzato un costruttore di tipo ` Array ` con più di un argomento.

Perché è un problema?

Il costruttore Array presenta una semantica ambigua:

  • new Array() crea un array vuoto.
  • new Array(42) crea un array con 42 elementi.
  • new Array(42, 43) crea un array con due elementi, 42 e 43.

Esempio

import QtQuick

Item {
    function createArray() {
        return new Array(1, 2, 3)
    }
}

Per risolvere questo avviso, utilizzare ` [...] ` invece di ` new Array(...)`.

funzioni:

import QtQuick

Item {
    function createArray() {
        return [1, 2, 3]
    }
}

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.