【问题标题】:Kotlin - how to iterate over a map or a list inside a builder blockKotlin - 如何在构建器块内迭代地图或列表
【发布时间】:2020-05-18 21:41:57
【问题描述】:

可能是一个愚蠢的问题,但我想知道是否可以在构建器块内迭代地图或列表?

我正在构建HttpRequest,我想在列表或标题地图之上工作。例如,让我们想象一下这种情况:

val headers1 = hashMapOf("Content-type" to "application/json")
val headers2 = listOf("Content-type=application/json")

我真的更喜欢使用地图而不是传递String=String 的列表,但如果它更简单或更简洁,我可以接受。

这是我构建 HttpRequest 的方式:

HttpRequest.newBuilder()
    .version(HttpClient.Version.HTTP_1_1)
    .timeout(Duration.ofSeconds(1))
    .uri(URI.create(endpoint))
    .method(method.value, HttpRequest.BodyPublishers.ofString(body))
    .header(<inject headers here>)
    .build()

是否可以在构建过程中添加/注入标头?

【问题讨论】:

    标签: kotlin


    【解决方案1】:

    你可以像这样遍历地图

    val headers: Map<String, String> = /* ... */
    
    HttpRequest.newBuilder()
        .version(HttpClient.Version.HTTP_1_1)
        .timeout(Duration.ofSeconds(1))
        .uri(URI.create(endpoint))
        .method(method.value, HttpRequest.BodyPublishers.ofString(body))
        .apply {
            headers.forEach { (key, value) -> setRequestHeader(key, value) }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-09
      • 2018-02-16
      • 1970-01-01
      • 1970-01-01
      • 2013-09-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多