【问题标题】:Kotlin - "run" for static Java methodsKotlin - 静态 Java 方法的“运行”
【发布时间】:2019-08-15 03:33:48
【问题描述】:

我有以下代码:

import javax.swing.*
...
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName())
UIManager.put("ToolTip.border", BorderFactory.createEmptyBorder())
UIManager.put("PopupMenu.border", BorderFactory.createEmptyBorder())
...

我想去掉所有UIManager. 限定符,像这样:

UIManager.run {
    setLookAndFeel(getCrossPlatformLookAndFeelClassName())
    put("ToolTip.border", BorderFactory.createEmptyBorder())
    put("PopupMenu.border", BorderFactory.createEmptyBorder())
    ...
}

当然,这段代码无法编译。有没有可能实现?

【问题讨论】:

  • import javax.swing.UIManager.*
  • 我不想在其他方法中污染命名空间。
  • 如果不制作包装器,我看不到其他选项。如果您不喜欢通用名称put,您可以使用另一个名称创建一个实用方法并调用该方法。或者创建一个 object 来包装对 UIManager 的每次调用,然后在该对象上调用 run

标签: kotlin extension-methods static-methods


【解决方案1】:

您可以使用“with”关键字来实现。这是 Kotlin 中的作用域函数之一。

with(UIManager)
{
    setLookAndFeel(getCrossPlatformLookAndFeelClassName())
    put("ToolTip.border", BorderFactory.createEmptyBorder())
    put("PopupMenu.border", BorderFactory.createEmptyBorder())
    ...
}

最终你会期待某种范围函数。这篇文章详细解释了 Kotlin 中每个范围函数的用例。 https://medium.com/@elye.project/mastering-kotlin-standard-functions-run-with-let-also-and-apply-9cd334b0ef84

【讨论】:

  • 您的代码格式与 Java/Kotlin 约定不匹配 kotlinlang.org/docs/reference/…
  • @Eugene 我不完全明白你的意思。
  • For curly braces, put the opening brace in the end of the line where the construct begins, and the closing brace on a separate line aligned horizontally with the opening construct.
  • Classifier 'UIManager' does not have a companion object, and thus must be initialized here.
  • @dyukha 是的,这是个问题。没有尝试使用java static。调查它。如果我能解决这个问题,会更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-07-22
  • 1970-01-01
  • 2011-05-14
  • 2014-01-09
  • 2017-01-03
  • 2017-03-14
  • 2015-03-28
相关资源
最近更新 更多