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

时间:2019-03-24 21:03:14

标签: kotlin extension-methods static-methods

我有以下代码:

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())
    ...
}

当然,此代码不会编译。有可能实现吗?

1 个答案:

答案 0 :(得分:-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