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

Kotlin语言中`字符的作用是什么?仅见过System.`in`的使用场景

Understanding Backticks () in Kotlin for System.`in``

Hey there! Let me break down what those backticks are doing in your System.in`` example—they’re a handy Kotlin feature that solves a specific naming conflict problem.

Core Purpose: Escaping Keywords as Identifiers

The biggest use case for backticks in Kotlin is letting you use Kotlin keywords as valid identifiers (variable names, function names, or in this case, a Java field name).

Here’s the breakdown with your example:

  • in is a reserved keyword in Kotlin—you’ll recognize it from loops like for (item in myList) or check expressions like if (x in 1..10).
  • But in Java’s standard library, there’s a static field called System.in (used for input streams). If you tried to write System.in directly in Kotlin, the compiler would throw an error because it thinks in is a keyword, not a field name.
  • Wrapping in in backticks (System.in``) tells the Kotlin compiler: "Treat this as a literal name, not a keyword"—so it correctly references the Java System.in field.

Other Common Uses for Backticks

Backticks aren’t just for Java interop—they have a few other practical uses:

  • Calling Java methods/fields with Kotlin keyword names: If a Java class has a method named is() (and is is a Kotlin keyword), you’d call it as myJavaObj.is``() in Kotlin.
  • Testing-friendly naming: In test functions, you can use backticks to write descriptive, sentence-like names (e.g., fun calculates total when items are added() { ... }). This makes test reports much easier to read!
  • Avoiding naming collisions: If you need to use a name that’s already a keyword for some edge case (though this is generally not recommended for readability), backticks let you do it—like val class = "MyClass".

So next time you see backticks in Kotlin, it’s almost always about telling the compiler to treat a keyword (or unusual name) as a plain identifier. Your System.in`` example is a classic case of Kotlin playing nice with Java’s existing APIs!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:36:46