gpt4 book ai didi

kotlin - 在 Kotlin 中实现接口(interface)

转载 作者:行者123 更新时间:2023-12-02 13:37:35 24 4
gpt4 key购买 nike

谁能向我解释这个接口(interface)实现的语法?
为什么我需要使用符号 '=' 来实现 CommandLineRunner。当我使用符号 ':'(根据基本语法 http://kotlinlang.org/docs/reference/interfaces.html )编译器需要返回语句。

@SpringBootApplication 
class Application{

@Bean
fun imageProcess(repo: MongoRepository) = CommandLineRunner {
val room2 = Room(id ="1AN1",
primaryUnit = "XYZ")
repo.save(room)}}

@FunctionalInterface
public interface CommandLineRunner {
void run(String... args) throws Exception;}

最佳答案

好吧,假设这个编译(不清楚,因为你缺少函数的主体),那么以下是正确的:
imageProcess返回 CommandLineRunner .您可以省略功能 block 周围的大括号,只需使用此处的表达式主体功能即可。

表达式体函数是其主体为表达式的函数(其中表达式是解析为特定类型值的代码块)。

https://kotlinlang.org/docs/reference/lambdas.html

以这些为例:

// 1 + 2 + 3 is an expression that resolves to an Integer value. 
// Therefore, the return type is Int
fun intExpression() = 1 + 2 + 3

// false && true is an expression that resolves to a Boolean value.
// Therefore, the return type is Boolean
fun boolExpression() = false && true

// The when here is a fully exhaustive when expression
// It can resolve to an Integer or a String.
// Therefore the return type is the common subtype of both
// Integer and String which happens to be Any (the root of the Kotlin type heirarchy.
fun anyExpression(foo: Boolean) = when(foo) {
true -> 1
else -> "Hello"
}

表达式的更正式定义:

https://blog.kotlin-academy.com/kotlin-programmer-dictionary-statement-vs-expression-e6743ba1aaa0

编辑1:

为了进一步澄清,实际发生的是您正在创建 CommandLineRunner 的匿名实现。界面。由于接口(interface)定义了一个抽象方法,因此只能以您编写的方式编写。这意味着您的 CommandLineRunner interface 是 SAM 类型,编译器正在执行 SAM 类型转换。换句话说,您可以这样编写代码:
class MyCommandLineRunner(repo: MongoRepository) : CommandLineRunner {
override fun run(args: String) {
// Do stuff...
}
}

fun imageProcess(repo: MongoRepository) = MyCommandLineRunner(repo)

但是,您不需要这样做,因为接口(interface)只有一个抽象方法,因此您可以简单地定义接口(interface)的内联实现,而无需显式覆盖 run功能。

在此处阅读有关 SAM 类型和 SAM 转换的信息:

https://kotlinlang.org/docs/reference/java-interop.html#sam-conversions

编辑2:

最后,看这里:

https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/CommandLineRunner.html

那是您正在实现的接口(interface)。如您所见,它确实符合 SAM 类型的定义,这就是为什么您可以创建它的内联实现而不显式声明 run 的覆盖。功能。如果接口(interface)有一个额外的方法(比如说 stop ),那么你必须像这样编写你的匿名实现:
@Bean
fun imageProcess(repo: MongoRepository) = object : CommandLineRunner {
override fun run(args: String) {
// Do stuff
}

override fun stop() {
// Do stuff
}
}

关于kotlin - 在 Kotlin 中实现接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52871655/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com