Tag: 句法

如何在Kotlin中声明和初始化MutableSet?

如何将MutableSet<int>变量声明为{1,2,3}?

我怎么能在Kotlin做一个换行符(续行)

我有很长的一行代码,我想分解成多行。 我使用什么语法? 例如,添加一堆字符串: val text = "This " + "is " + "a " + "long " + "long " + "line"

Kotlin默认参数:禁止零参数调用

在我的项目中,我有一个这样的功能: fun doCoolStuff(arg1: Int = 0, arg2: String? = null) { } 我希望在下列情况下使用它: obj.doCoolStuff(101) // only first argument provided obj.doCoolStuff("102") // only second argument provided obj.doCoolStuff(103, "104") // both arguments provided 但不是在这个: obj.doCoolStuff() // illegal case, should not be able to call the function like this 我如何在语法级别实现这一点?

Kotlin:创建地图时的条件项目

在Kotlin有没有办法做这样的事情? mapOf( "key1" to var1, "key2" to var2, if(var3 > 5) "key3" to var3 ) 或者唯一的方法是在地图创建后添加键“key3”? 我只想在某些条件满足的情况下将项目添加到地图中。

Kotlin:访问when语句的参数

有没有办法获得我传入when语句的表达式的值? 在我的应用程序中,我有一个这样的KeyListener _content.addKeyListener(object : KeyAdapter() { override fun keyPressed(e: KeyEvent?) = when(e?.keyCode) { KeyEvent.VK_T -> mainWindow.enterTrainingState() KeyEvent.VK_P -> mainWindow.enterPlayState() KeyEvent.VK_E -> mainWindow.close() else -> println(e?.keyCode) } }) Kotlin有一个整洁的语法来访问e?.keyCode ? 我真的不想重复这个表达。

在Kotlin多行字符串中转义的模板

如果我想在多行字符串中使用$符号,我该如何逃避它? val condition = """ … $eq … """ $eq被解析为对变量的引用。 如何逃避$ ,以便它不会被认为是参考变量? (Kotlin M13)

有趣的运算符'==='在Kotlin

什么运算符'==='在Kotlin中做什么? 它是如何工作的? 我们可以检查参考平等吗? val a: Int = 10000 print(a === a) // Prints 'true' val boxedA: Int? = a val anotherBoxedA: Int? = a print(boxedA === anotherBoxedA) // !!!Prints 'false'!!! 但在以下情况下: var a : Int = 1000 var b : Int = 1000 println(a === b) // print 'true' !!! val a: Int = 1000和val […]

变量名称前的Kotlin星号运算符或Kotlin中的Spread运算符

我想知道在Kotlin中变量名称前面的星号是什么。 我在Spring引导Kotlin例子中看到了这个( *args ): @SpringBootApplication open class Application { @Bean open fun init(repository: CustomerRepository) = CommandLineRunner { repository.save(Customer("Jack", "Bauer")) repository.save(Customer("Chloe", "O'Brian")) repository.save(Customer("Kim", "Bauer")) repository.save(Customer("David", "Palmer")) repository.save(Customer("Michelle", "Dessler")) } } fun main(args: Array<String>) { SpringApplication.run(Application::class.java, *args) }