Что значит Name shadowed: tsn для этого кода в idea
- User
Что значит Name shadowed: tsn для этого кода в idea
- Assistant
Сообщение "Name shadowed: tsn" в IntelliJ IDEA (или другом IDE на базе платформы JetBrains) означает, что в вашем коде переменная, параметр или имя функции затеняет (shadowing) другое имя с таким же идентификатором
tsnиз более внешней области видимости.Что такое shadowing (затенение)
Затенение — ситуация, когда внутри одной области видимости объявляется переменная или параметр с именем, которое уже используется в более внешней области (например, в глобальной области, в теле функции, в родительском блоке и т.п.). В результате, внутри внутреннего блока с таким именем работает именно локальная переменная, а внешняя становится "невидимой".
Пример:
val tsn = "outer" fun example() { val tsn = "inner" // <-- Затеняет внешнее `tsn` println(tsn) }В этом примере внутренний
tsnзатеняет внешнийtsn.Почему это предупреждение полезно
- Может привести к путанице и ошибкам.
- Спутать, какую именно переменную вы используете.
- Ухудшает читаемость кода.
Как убрать предупреждение
- Переименовать внутреннюю переменную (или параметр), чтобы оно не совпадало с более внешней.
- Или если затенение оправдано — можно проигнорировать предупреждение.
Если хотите, можете показать код, где возникает это предупреждение, я помогу разобраться точнее.
- User
ItemType.TRANSPORT -> { validateCurrentBase(tsn.consumptionTotal, tsn.machineOperation) } ItemType.COST -> { tsn.tsn.forEach { tsn -> validateTotalCurrent(tsn, form19) }
validateCurrentBase(tsn.quantityTotal, tsn.workersSalary) validateCurrentBase(tsn.quantityTotal, tsn.machineOperation) validateCurrentBase(tsn.quantityTotal, tsn.machinistSalary) validateCurrentBase(tsn.quantityTotal, tsn.materialResources) validateCurrentBase(tsn.quantityTotal, tsn.equipmentCosts) validateCurrentBase(tsn.quantityTotal, tsn.otherCosts) } - Assistant
Спасибо за код! Проблема связана с именем
tsn, которое вы используете в разных контекстах, в частности — в лямбде:tsn.tsn.forEach { tsn -> // тело }Здесь в
.forEachпараметр лямбды тоже называетсяtsn. Это затеняет внешнийtsn, который, судя по вашему коду, является некоторым объектом, у которого вы берёте свойства (tsn.consumptionTotal,tsn.machineOperation, и т.д.).
Что именно происходит
- Внешний
tsn— объект (например, параметр функции, или локальная переменная). - Вы вызываете
tsn.tsn.forEach { tsn -> ... } - Внутри тела лямбды
tsn— это элемент из коллекцииtsn.tsn. - Лямбда-параметр с таким же именем как внешний объект затеняет этот внешний объект.
- Поэтому IDE и предупреждает: Name shadowed: tsn
Как исправить
Просто дайте лямбда-параметру другое уникальное имя, чтобы не затенять внешний:
tsn.tsn.forEach { innerTsn -> validateTotalCurrent(innerTsn, form19) }Или другое подходящее имя, например
item,elementи т.п.
Итог — исправленный кусок
ItemType.COST -> { tsn.tsn.forEach { innerTsn -> validateTotalCurrent(innerTsn, form19) } validateCurrentBase(tsn.quantityTotal, tsn.workersSalary) validateCurrentBase(tsn.quantityTotal, tsn.machineOperation) validateCurrentBase(tsn.quantityTotal, tsn.machinistSalary) validateCurrentBase(tsn.quantityTotal, tsn.materialResources) validateCurrentBase(tsn.quantityTotal, tsn.equipmentCosts) validateCurrentBase(tsn.quantityTotal, tsn.otherCosts) }Таким образом, вы уберёте предупреждение
Name shadowed: tsn. - Внешний
- User
anable/disable rules in SonarQube in IDEA
- Assistant
In IntelliJ IDEA, if you are using SonarQube integrations—either via the SonarLint plugin (which performs on-the-fly analysis locally) or connecting to a SonarQube server—you might want to enable or disable some Sonar rules. Here's how you can manage rules in SonarQube from IntelliJ IDEA and related tools.
1. SonarLint (local analysis)
SonarLint is a free plugin in IntelliJ IDEA that gives instant feedback on code quality issues locally.
Enable/Disable rules in SonarLint:
-
SonarLint uses its own ruleset or can be connected to a SonarQube server project rules.
-
To configure rules locally:
-
Open Settings (Preferences on macOS):
File -> Settings -> Other Settings -> SonarLint -
Bind project to SonarQube server (optional) so SonarLint uses the server's quality profile:
In "Connected Mode" tab, connect to your SonarQube server and bind to a project. -
Locally, SonarLint does not provide a GUI to enable/disable individual rules directly inside IDEA.
However, you can configure sonarlint rules activation via the SonarQube server, if connected. -
If working offline, to customize the rules enabled for analysis, you can add a
sonarlint.jsonconfiguration file in your project root, but this is uncommon and limited.
-
2. Manage Rules in SonarQube Server (recommended for team)
Most projects manage rules and quality profiles on the SonarQube server. This is the centralized and recommended way.
How to enable/disable rules in SonarQube:
-
Open your SonarQube server in a web browser.
-
Log in as an administrator or a user with permissions to manage quality profiles.
-
Go to Quality Profiles section.
-
Select the language you want to configure.
-
Select the active profile (e.g., "Sonar way").
-
Here you can:
- Activate rules
- Deactivate rules
- Adjust rule parameters
-
Save changes.
Your project bound to this profile will now respect the updated rules.
3. Sync SonarLint with SonarQube server rules
If your IntelliJ IDEA project is connected to the SonarQube server in Connected Mode:
-
SonarLint will use the server's quality profile.
-
Any change of active rules on the server will be reflected when SonarLint syncs.
-
To force a sync, go to:
View -> Tool Windows -> SonarLint(or use the SonarLint menu), and select "Update all project bindings" or similar option.
Summary
Task How to do it Location Enable/disable rules Manage Quality Profiles on SonarQube UI SonarQube server Use updated rules in IDEA Bind project & enable Connected Mode in SonarLint plugin IntelliJ IDEA + SonarLint plugin Disable rules locally (limited) Customize sonarlint.jsonor adjust SonarLint analysis scopeProject local
If you want a quick way to disable a rule for a specific code section in IDEA, you can use "Suppress warnings" comments:
@Suppress("ruleId") fun someFunction() { // code that triggers ruleId violation but is suppressed }Replace
"ruleId"with the specific SonarLint rule key.
References
- https://www.sonarlint.org/intellij/
- SonarQube documentation: https://docs.sonarqube.org/latest/user-guide/quality-profiles/
- SonarLint + Connected Mode docs: https://www.sonarlint.org/connected-mode/
If you want, I can guide you step-by-step for your particular setup!
-
- User
Включить правило проверки повторяющегося кода
- Assistant
Чтобы включить правило проверки повторяющегося кода (code duplication) в SonarQube и/или в SonarLint с интеграцией в IntelliJ IDEA, нужно понимать, как эта проверка реализована и где она настраивается.
Основные моменты
- Проверка дублирования кода — это отдельный анализ в SonarQube, который не всегда реализуется как отдельное правило в Quality Profile.
- Обычно дублирование кода (копипаст) проверяется встроенным анализатором дублирования SonarQube и конфигурируется в настройках профиля качества проекта или глобальных настройках.
Как включить проверку дублирования кода в SonarQube
-
На сервере SonarQube:
-
Перейдите в Администрирование > Общие настройки > Дублирование (Administration > General Settings > Duplication)
Здесь можно настроить параметры обнаружения дублирования, минимальную длину блока и т.п. -
Далее проверьте, что анализ дублирования включён для нужного проекта и языка. Обычно он включён по умолчанию.
-
-
Quality Profile (Профиль качества) для языка
- В разделе Quality Profiles, выберите профиль для вашего языка.
- Правила, отвечающие за дублирование, обычно помечаются как "Code Smell" или "Bug", но проверка дублирования — это отдельный модуль, не всегда представлен отдельным правилом.
- Иногда в профиле можно встретить правило типа
"Duplicated Blocks Should Not Exist" — оно должно быть активировано.
Если такого правила нет, просто проверьте настройки дублирования в Общих настройках.
Как включить проверку дублирования кода при локальном анализе в IntelliJ IDEA
- SonarLint не поддерживает локальную проверку дублирования кода (duplicated blocks) на момент написания.
- Проверка дублирования делается на стороне SonarQube сервера.
Итог: что сделать
-
Проверьте настройки проекта в SonarQube:
- Включено ли сканирование для дублированного кода.
- Подключён ли к профилю качества, в котором включена проверка дублирования.
-
Настройте параметры дублирования:
- Как минимум, это порог размера дублированного блока (в строках или токенах).
-
Перезапустите анализ в SonarQube и посмотрите отчёты по дублированию.
Дополнительно
- Можно подавлять предупреждения дублирования на уровне кода (например,
NOSONARили@SuppressWarnings), но обычно этого не требуется.
Если подскажете, что именно вы используете (SonarQube сервер, SonarLint, какая версия), могу подсказать более конкретные шаги. Могу помочь с настройкой и показом примеров!
- User
Почему дублированный код не помечается sonar cube и даже правила такого нет: org.sonarlint.intellij.util.CompoundIcon@496964eb true org.sonarlint.intellij.util.CompoundIcon@25e69b6f true org.sonarlint.intellij.util.CompoundIcon@19bb1b91 true org.sonarlint.intellij.util.CompoundIcon@56aaed3a true org.sonarlint.intellij.util.CompoundIcon@54e69538 true org.sonarlint.intellij.util.CompoundIcon@45ca4128 true org.sonarlint.intellij.util.CompoundIcon@4ecbd93 true org.sonarlint.intellij.util.CompoundIcon@52e4309 true org.sonarlint.intellij.util.CompoundIcon@650159c1 true org.sonarlint.intellij.util.CompoundIcon@72d59748 true org.sonarlint.intellij.util.CompoundIcon@13b4bca4 false org.sonarlint.intellij.util.CompoundIcon@64f583d0 true org.sonarlint.intellij.util.CompoundIcon@b5511de true org.sonarlint.intellij.util.CompoundIcon@55e4a82b true org.sonarlint.intellij.util.CompoundIcon@63037faf true org.sonarlint.intellij.util.CompoundIcon@2b209b1c true org.sonarlint.intellij.util.CompoundIcon@858b447 false org.sonarlint.intellij.util.CompoundIcon@780de097 false org.sonarlint.intellij.util.CompoundIcon@8b063e true org.sonarlint.intellij.util.CompoundIcon@2fdc9548 false org.sonarlint.intellij.util.CompoundIcon@62ebe678 true org.sonarlint.intellij.util.CompoundIcon@7575abea true org.sonarlint.intellij.util.CompoundIcon@2d17e98c true org.sonarlint.intellij.util.CompoundIcon@66aa5fb3 true org.sonarlint.intellij.util.CompoundIcon@5bcfad38 true org.sonarlint.intellij.util.CompoundIcon@33d6750 true org.sonarlint.intellij.util.CompoundIcon@1174b532 true org.sonarlint.intellij.util.CompoundIcon@25172768 true org.sonarlint.intellij.util.CompoundIcon@317e89f true org.sonarlint.intellij.util.CompoundIcon@6bf8184a true org.sonarlint.intellij.util.CompoundIcon@5f91ed22 true org.sonarlint.intellij.util.CompoundIcon@4321bddf true org.sonarlint.intellij.util.CompoundIcon@7f4ef634 true org.sonarlint.intellij.util.CompoundIcon@54df8bdf true org.sonarlint.intellij.util.CompoundIcon@477949b true org.sonarlint.intellij.util.CompoundIcon@4af60e8f true org.sonarlint.intellij.util.CompoundIcon@4201beb3 true org.sonarlint.intellij.util.CompoundIcon@6aa8545f true org.sonarlint.intellij.util.CompoundIcon@5243d6dd true org.sonarlint.intellij.util.CompoundIcon@28bb386c false org.sonarlint.intellij.util.CompoundIcon@6780ffee true org.sonarlint.intellij.util.CompoundIcon@4f2255ed true org.sonarlint.intellij.util.CompoundIcon@31b87ea true org.sonarlint.intellij.util.CompoundIcon@7212a7bd true org.sonarlint.intellij.util.CompoundIcon@120d599e true org.sonarlint.intellij.util.CompoundIcon@4f5deb0f true org.sonarlint.intellij.util.CompoundIcon@10a601d9 true org.sonarlint.intellij.util.CompoundIcon@776e633f true org.sonarlint.intellij.util.CompoundIcon@fd715e5 true org.sonarlint.intellij.util.CompoundIcon@2ff29283 true org.sonarlint.intellij.util.CompoundIcon@f7ae66d true org.sonarlint.intellij.util.CompoundIcon@b891b26 true org.sonarlint.intellij.util.CompoundIcon@3cc65f8f true org.sonarlint.intellij.util.CompoundIcon@79bb41e true org.sonarlint.intellij.util.CompoundIcon@5f8a730e false org.sonarlint.intellij.util.CompoundIcon@1c9903f2 true org.sonarlint.intellij.util.CompoundIcon@12ad1dc9 false org.sonarlint.intellij.util.CompoundIcon@484c60c6 true org.sonarlint.intellij.util.CompoundIcon@445268c2 true org.sonarlint.intellij.util.CompoundIcon@10006529 true org.sonarlint.intellij.util.CompoundIcon@6a3971b5 true org.sonarlint.intellij.util.CompoundIcon@41d86664 true org.sonarlint.intellij.util.CompoundIcon@169b12e5 true org.sonarlint.intellij.util.CompoundIcon@5a10432 true org.sonarlint.intellij.util.CompoundIcon@24b479ea false org.sonarlint.intellij.util.CompoundIcon@265dd05e true org.sonarlint.intellij.util.CompoundIcon@681fe24a true org.sonarlint.intellij.util.CompoundIcon@6512fbef true org.sonarlint.intellij.util.CompoundIcon@62eeb58e true org.sonarlint.intellij.util.CompoundIcon@2af946ad true org.sonarlint.intellij.util.CompoundIcon@3d63ec0a true org.sonarlint.intellij.util.CompoundIcon@4fdca5ca true org.sonarlint.intellij.util.CompoundIcon@58892b7a true org.sonarlint.intellij.util.CompoundIcon@3825c2e8 true org.sonarlint.intellij.util.CompoundIcon@1a047a5a false org.sonarlint.intellij.util.CompoundIcon@305c7e25 false org.sonarlint.intellij.util.CompoundIcon@219f41af false org.sonarlint.intellij.util.CompoundIcon@37bbe5f6 true org.sonarlint.intellij.util.CompoundIcon@e548ff1 true org.sonarlint.intellij.util.CompoundIcon@5daa6548 true org.sonarlint.intellij.util.CompoundIcon@663d56b true org.sonarlint.intellij.util.CompoundIcon@6e9f0404 true org.sonarlint.intellij.util.CompoundIcon@449e3521 true org.sonarlint.intellij.util.CompoundIcon@4a9088df true org.sonarlint.intellij.util.CompoundIcon@52c0c46b true org.sonarlint.intellij.util.CompoundIcon@44694513 true org.sonarlint.intellij.util.CompoundIcon@716b5782 true org.sonarlint.intellij.util.CompoundIcon@3f73ef00 true org.sonarlint.intellij.util.CompoundIcon@6b449719 true org.sonarlint.intellij.util.CompoundIcon@658b16bf true org.sonarlint.intellij.util.CompoundIcon@4ef78acb true org.sonarlint.intellij.util.CompoundIcon@6e5c77fa true org.sonarlint.intellij.util.CompoundIcon@216fd977 true org.sonarlint.intellij.util.CompoundIcon@1c6c1d0b true org.sonarlint.intellij.util.CompoundIcon@6ebf7d9f true org.sonarlint.intellij.util.CompoundIcon@63d12415 true org.sonarlint.intellij.util.CompoundIcon@3caaed79 true org.sonarlint.intellij.util.CompoundIcon@40d23ba2 true org.sonarlint.intellij.util.CompoundIcon@5594e5a2 true org.sonarlint.intellij.util.CompoundIcon@3f8f9289 true org.sonarlint.intellij.util.CompoundIcon@54a56124 true org.sonarlint.intellij.util.CompoundIcon@57b4f39 true org.sonarlint.intellij.util.CompoundIcon@773013c1 true org.sonarlint.intellij.util.CompoundIcon@34e8dc74 false org.sonarlint.intellij.util.CompoundIcon@4b3b278c true org.sonarlint.intellij.util.CompoundIcon@1466bb55 true org.sonarlint.intellij.util.CompoundIcon@633f1c03 true org.sonarlint.intellij.util.CompoundIcon@11c6676c true org.sonarlint.intellij.util.CompoundIcon@3d3359f false org.sonarlint.intellij.util.CompoundIcon@22ce8aa3 true org.sonarlint.intellij.util.CompoundIcon@398a55fd true org.sonarlint.intellij.util.CompoundIcon@1bd5b8a7 false org.sonarlint.intellij.util.CompoundIcon@1b0098f true org.sonarlint.intellij.util.CompoundIcon@577d0088 true org.sonarlint.intellij.util.CompoundIcon@3cb39227 false org.sonarlint.intellij.util.CompoundIcon@a151596 true org.sonarlint.intellij.util.CompoundIcon@b68992a true org.sonarlint.intellij.util.CompoundIcon@34aeb18f false org.sonarlint.intellij.util.CompoundIcon@14ac3f97 true org.sonarlint.intellij.util.CompoundIcon@36b72131 true org.sonarlint.intellij.util.CompoundIcon@79d95f04 true org.sonarlint.intellij.util.CompoundIcon@38babb79 true org.sonarlint.intellij.util.CompoundIcon@4d9f6b7e true org.sonarlint.intellij.util.CompoundIcon@422e7555 true org.sonarlint.intellij.util.CompoundIcon@71bc236b true org.sonarlint.intellij.util.CompoundIcon@1c302f56 true org.sonarlint.intellij.util.CompoundIcon@2a427335 true org.sonarlint.intellij.util.CompoundIcon@1bf73ff5 true
- Assistant
Проблема, с которой вы столкнулись — dублирование кода не помечается в SonarLint/IntelliJ IDEA, и при этом в списке правил нет отдельного правила для проверки дублированного кода.
Это классическая особенность работы SonarQube и SonarLint.
Почему так происходит
-
Проверка дублирования кода — это специальный анализ, который работает только на уровне SonarQube сервера
- SonarQube выполняет анализ дублирования отдельно от правил Quality Profile.
- В SonarQube нет отдельного "правила" для дублирования, которое можно включать или выключать — дублирование кода анализируется как отдельный механизм (дубликаты находятся по сложным критериям).
-
SonarLint не поддерживает локальную проверку дублирования
- SonarLint выполняет проверку на уровне правил (issues) из Quality Profile.
- Но дублирование — это аналитика, которую SonarLint не делает, т.к. для обнаружения дублирования нужен полный проектный или многомодульный анализ.
- Поэтому в IDE вы не увидите подсветку дублированного кода из SonarLint.
-
Отсутствие правила дублирования в списках правил и в IntelliJ вызвано тем, что дублирование не является правилом Quality Profile.
Что вам делать, чтобы видеть дублирование и управлять им
-
Анализируйте проект на стороне SonarQube Server
- Запустите сканирование через SonarScanner или CI.
- В отчетах сервера SonarQube будет отображён дубликатный код (обычно в разделе "Duplications").
- Там можно увидеть где и сколько дублирования.
-
Настройте пороги обнаружения дублирования на сервере
- В настройках SonarQube (Admin -> General Settings -> Duplication) задайте минимальный размер дублирования (кол-во строк, токенов).
- Так же можно ограничить анализ по языкам.
-
Подключите IntelliJ IDEA к SonarQube в Connected Mode
- Это позволит получить правила и дефекты из Quality Profile, но дублирование всё равно не проанализируется в локальном режиме.
-
Используйте сторонние инструменты для поиска дублирующегося кода в IDE
- IntelliJ IDEA содержит собственный механизм (Code > Locate Duplicates), который хорошо работает на локальном уровне.
- Он может помочь искать дублирование автоматически при разработке.
Относительно вашего вывода с
org.sonarlint.intellij.util.CompoundIcon@...- Это скорее всего вывод из логов плагина SonarLint или из дебага, связанный с отображением иконок в инспекциях.
- Не имеет отношения напрямую к проверке дублирования.
- Видимо, вы смотрите в список правил или ошибок, где элементы представлены такими объектами.
Кратко
Вопрос Ответ Есть ли правило проверки дублирования в SonarQube? Нет отдельного правила — это отдельный механизм дублирования SonarLint проверяет дублирование? Нет, SonarLint не анализирует дублирование локально Как увидеть дублирование? Анализируйте на сервере SonarQube, смотрите вкладку Duplications Можно ли включить/отключить? Настраивается порог дублирования в настройках SonarQube
Если хотите, могу помочь с шагами по запуску анализа с дублированием и как посмотреть результаты на сервере или посоветовать инструменты для локального поиска дубликатов на уровне IDE.
-