在Kotlin中实现接口

时间:2018-10-18 10:06:42

标签: kotlin interface implementation

有人可以向我解释此接口实现的语法吗? 为什么我需要使用符号“ =”来实现CommandLineRunner。当我使用符号':'(根据基本语法http://kotlinlang.org/docs/reference/interfaces.html)时,编译器需要一个return语句。

@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;}

1 个答案:

答案 0 :(得分:1)

好吧,假设此代码可以编译(由于您缺少函数的主体而不清楚),则以下内容是正确的:

must返回一个must_not。您可以省略功能块周围的花括号,而只需像此处使用的那样使用表达式固定函数。

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

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

以这些为例:

imageProcess

表达式的更正式定义:

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

编辑1:

为进一步说明,实际上是在创建CommandLineRunner接口的匿名实现。由于接口定义了一个抽象方法,因此只能以您编写的方式编写。这意味着您的// 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" } 接口是SAM类型,并且编译器正在执行SAM类型转换。换句话说,您可以这样编写代码:

CommandLineRunner

但是,您不需要这样做,因为接口只有一个抽象方法,因此您可以简单地定义接口的内联实现,而不必显式覆盖CommandLineRunner函数。

在此处了解有关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

这是您正在实现的接口。如您所见,它确实符合SAM类型的定义,这就是为什么您可以在不显式声明class MyCommandLineRunner(repo: MongoRepository) : CommandLineRunner { override fun run(args: String) { // Do stuff... } } fun imageProcess(repo: MongoRepository) = MyCommandLineRunner(repo) 函数的覆盖范围的情况下创建其内联实现的原因。如果接口有一个额外的方法(例如run),那么您将必须像这样编写匿名实现:

run