【问题标题】:How to convert this Java code to Kotlin Code?如何将此 Java 代码转换为 Kotlin 代码?
【发布时间】:2018-06-24 04:39:49
【问题描述】:

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

请告诉我如何更正此代码。

【问题讨论】:

标签: java spring-boot kotlin


【解决方案1】:

您的函数文字 / 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.
    }
}

【讨论】:

  • 这就是我需要的答案!另请参阅link 可以了解更多关于 SAM 转换的信息。谢谢您的帮助。
【解决方案2】:

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

// 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的转换有更好的了解。

【讨论】:

    猜你喜欢
    • 2019-11-19
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多