You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin中使用@Annotation与[Annotation]的区别是什么?

Great question! Let's break this down clearly because I can see where the confusion might be coming from.

First off, let's get one key point straight: Kotlin's official syntax does NOT support using square brackets [Annotation] for annotations. The example you shared with class LoggingService [Inject] (protected val logger: Logger) isn't valid Kotlin code—this is likely a typo, a formatting quirk from documentation, or confusion with another language/framework's syntax.

Now let's clarify the correct annotation patterns related to your example:

1. Annotating the primary constructor itself: @Inject after the class name

When you write:

class LoggingService @Inject (protected val logger: Logger)
// Which is equivalent to explicitly writing the `constructor` keyword:
class LoggingService @Inject constructor(protected val logger: Logger)

Here, @Inject is applied to the entire primary constructor. This tells dependency injection frameworks (like Dagger or Hilt) that this is the constructor they should use to create instances of LoggingService, and they need to automatically provide the required dependencies (in this case, the Logger instance).

2. Annotating a constructor parameter: @Inject before the parameter

If you wanted to apply the annotation directly to the logger parameter instead, the correct syntax would be:

class LoggingService(@Inject protected val logger: Logger)

Here, @Inject targets only the logger parameter, signaling the framework to inject an instance for this specific parameter. That said, this pattern is far less common in DI scenarios—usually we annotate the entire constructor to mark it as the injection point.

Why might you have seen [Inject]?

A few possible reasons:

  • Formatting error: Some docs use square brackets to denote optional elements or highlight annotations, which can be misread as actual code syntax.
  • Cross-language confusion: Other JVM languages might use square brackets for annotations, but Kotlin sticks strictly to the @ prefix.
  • Custom DSLs: Rarely, some frameworks might define a custom DSL that uses square brackets as a syntactic shortcut, but this isn't part of standard Kotlin.

To wrap up:

  • Stick with @Annotation syntax for all standard Kotlin annotations—[Annotation] isn't valid.
  • Your example class LoggingService @Inject (protected val logger: Logger) is the correct way to mark a class's primary constructor for dependency injection.

内容的提问来源于stack exchange,提问作者Flickster

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:22:58