如何将此Java代码转换为Kotlin代码?
我正在学习春季引导和新kotlin。 此Java函数转换为kotlin代码时将报告错误。 如何重写这个kotlin函数?
https://spring.io/guides/gs/consuming-rest/
@Bean public CommandLineRunner run(RestTemplate restTemplate) throws Exception { return args -> { Quote quote = restTemplate.getForObject( "http://gturnquist-quoters.cfapps.io/api/random", Quote.class); log.info(quote.toString()); }; }
将这些代码转换成kotlin后,
@Bean @Throws(Exception::class) fun run(restTemplate: RestTemplate): CommandLineRunner { return { args -> val quote = restTemplate.getForObject( "http://gturnquist-quoters.cfapps.io/api/random", Quote::class.java) log.info(quote.toString()) } }
请告诉我如何更正此代码。
你的函数literal / lambda不是很正确。 为了使编译器能够将其转换为Java接口CommandLineRunner
的实际实现,请使用SAM转换 。
然后看起来如下:
fun run(restTemplate: RestTemplate): CommandLineRunner { return CommandLineRunner { args -> TODO("not implemented") } }
注意CommandLineRunner { args ->...}
或者,没有SAM转换, object
语法很方便:
return object : CommandLineRunner { override fun run(vararg args: String?) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } }
下面是将标准java接口转换为kotlin的kotlin basic的一些例子
// java interface CommandLineRunner { public void run(String... args); } // kotlin fun foo(): CommandLineRunner { return object: CommandLineRunner { override fun run(args: Array) { // TODO } } }
如果是function接口,则可以使用SAM转换
// java @FunctionalInterface interface CommandLineRunner { public void run(String... args); } // kotlin fun foo(): CommandLineRunner { return CommandLineRunner { args -> } }
希望你能更好的了解java到kotlin的转换。