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

问题描述 投票:3回答:1

我有以下代码:

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

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

kotlin extension-methods static-methods
1个回答
-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

© www.soinside.com 2019 - 2024. All rights reserved.