有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

spring boot如何将此Java代码转换为Kotlin代码?

我正在学习spring boot和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());
    };
}

idea将这些代码转换为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())
    }
}

Type mismatch

请告诉我如何更正此代码


共 (2) 个答案

  1. # 1 楼答案

    你的函数literal/lambda不太正确。为了使编译器能够将其转换为Java接口CommandLineRunner的实际实现,请使用SAM Conversion

    然后看起来如下:

    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.
        }
    }
    
  2. # 2 楼答案

    下面是kotlin basic将标准java接口转换为kotlin的一些示例

    // java
    interface CommandLineRunner {
        public void run(String... args);
    }
    
    
    // kotlin
    fun foo(): CommandLineRunner {
        return object: CommandLineRunner {
            override fun run(args: Array<String>) {
                // TODO
            }
        }
    }
    

    如果它是一个功能接口,那么可以使用SAM conversion

    // java
    @FunctionalInterface
    interface CommandLineRunner {
        public void run(String... args);
    }
    
    // kotlin
    fun foo(): CommandLineRunner {
        return CommandLineRunner { args ->
    
        }
    }
    

    希望您能更好地理解java到kotlin的转换