Kotlin - 静态 Java 方法的“运行”

Posted

技术标签:

【中文标题】Kotlin - 静态 Java 方法的“运行”【英文标题】:Kotlin - "run" for static Java methods 【发布时间】: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 【参考方案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。调查它。如果我能解决这个问题,会更新。

以上是关于Kotlin - 静态 Java 方法的“运行”的主要内容,如果未能解决你的问题,请参考以下文章

Kotlin定义静态变量静态方法

面向Kotlin与Java开发者的Dart快速入门静态变量枚举

使用Mockk模拟静态java方法

Kotlin 与 Java 相互调用

Kotlin CI 测试期间的静态最终变量初始化(Java 中)不正确

Kotlin基础初探