Tag: 函数

将多个方法合并为一个函数的方法

我是function风格编程的世界相当新的我正在尝试在Kotlin的一些代码,下面给出的代码片段是我所做的,但看起来这么强迫我 @EmailTemplate(“onCallTemplate”) fun retrieveNextOnCallCreateMailRecipientAndSendMail(time: LocalDateTime, trial: Boolean = true) { val emailTemplateID = extractEmailTemplateValue( “retrieveNextOnCallAndSendMail”) val messageTemplate = emailTemplateID?.let { messageTemplateAccessPoint.findByID(it) } val lisOfOnCalls = dataHubCommunicator .listOfOnCallToSendNotificationFromDataHub(time) val listOfMailRecipient = lisOfOnCalls ?.let { onCallListToMailRecipient.buildMailRecipientFromOnCalls(it) } listOfMailRecipient ?.let { messageTemplate ?.let { it1 -> emailSender .sendNotificationToOnCallPersons(it, it1, trial) } } log.info(“Message Has been sent Successfully”) } […]

Java不允许最终的默认方法..但是Kotlin?

如果您尝试在界面上创建内联函数,则会出现错误: ‘inline’ modifier is not allowed on virtual members. Only private or final members can be inlined ‘inline’ modifier is not allowed on virtual members. Only private or final members can be inlined 我明白,这是因为该function是虚拟的,因为它可以被覆盖。 如果我们能够声明“关闭”function,这些function将不是虚拟的,因此可以内联,这是非常有用的! 使用“私人”给我们一个非虚拟的“封闭”function,但是世界其他地方却不能使用它! 所以..有没有办法为抽象types定义“封闭的”非虚拟可嵌入函数? ( ps我打算自己回答这个问题,但可以自由分享你自己的答案! )

确保kotlin方法是静态的,顶级的或注释的@JvmStatic

如何将main声明为static,以便该方法按照以下方式运行(交互式): thufir@dur:~/kotlin$ thufir@dur:~/kotlin$ kotlinc Welcome to Kotlin version 1.1.51 (JRE 9.0.0.15+181) Type :help for help, :quit for quit >>> >>> println(“hello world”); WARNING: An illegal reflective access operation has occurred WARNING: Illegal reflective access by com.intellij.util.text.StringFactory to constructor java.lang.String(char[],boolean) WARNING: Please consider reporting this to the maintainers of com.intellij.util.text.StringFactory WARNING: Use –illegal-access=warn to enable warnings […]

如何将函数输出转换为Kotlin单元

我在Kotlin函数中遇到麻烦,应该返回Unit,但是由于使用了另一个返回布尔值的函数,会出现types不匹配的情况。 这是一个人为的例子: fun printAndReturnTrue(bar: Int): Boolean { println(bar) return true } fun foo(bar: Int): Unit = when(bar) { 0 -> println(“0”) else -> printAndReturnTrue(bar) } 在这里,我其实并不关心printAndReturnTrue返回一个布尔值的事实。 我只是想让富美执行副作用的操作。 但编译器警告types不匹配:我的else应该返回一个Unit值。 有没有一种很好的方法将值转换为Unit ? 我看到的最简单的解决方案是: fun foo(bar: Int): Unit = when(bar) { 0 -> println(“0”) else -> { printAndReturnTrue(bar) Unit } } 要么: fun foo(bar: Int): Unit = when(bar) […]

如何检查kotlin中的lambda空虚

如何检查Kotlin中的lambda是否为空? 例如,我有类似的签名 onError:(Throwable) -> Unit = {} 我怎么能不同的是它的默认值来应用到这个函数的身体或价值?