小编Jay*_*ard的帖子

在哪里/如何为Kotlin包添加文档?

在Java中,如果要记录包,则必须将其放入package-info.class文件中.对于Kotlin和KDoc来说,这仍然是一回事吗?我查看了一些Kotlin源代码,无法找到编写包文档的位置.

documentation package kotlin kdoc kotlin-dokka

6
推荐指数
1
解决办法
1097
查看次数

如何在Kotlin中的Java 8 Stream上调用collect(Collectors.toList())?

我有一些代码:

directoryChooser.title = "Select the directory"
val file = directoryChooser.showDialog(null)
if (file != null) {
    var files = Files.list(file.toPath())
            .filter { f ->
                f.fileName.endsWith("zip") && f.fileName.endsWith("ZIP")
                        && (f.fileName.startsWith("1207") || f.fileName.startsWith("4407") || f.fileName.startsWith("1507") || f.fileName.startsWith("9007") || f.fileName.startsWith("1807"))
            }
    for (f in files) {
        textArea.appendText(f.toString() + "\n")
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我collect(Collectors.toList())在过滤器结束时调用,我得到:

Error:(22, 13) Kotlin: [Internal Error] org.jetbrains.kotlin.codegen.CompilationException: Back-end (JVM) Internal error: no descriptor for type constructor of ('Captured(in ('Path'..'Path?'))'..'CapturedTypeConstructor(in ('Path'..'Path?'))?')
Cause: no descriptor for type constructor of ('Captured(in ('Path'..'Path?'))'..'CapturedTypeConstructor(in ('Path'..'Path?'))?')
File …
Run Code Online (Sandbox Code Playgroud)

java java-8 kotlin java-stream

6
推荐指数
1
解决办法
3230
查看次数

Kotlin有array.indexOf,但我无法弄清楚怎么做array.indexOfBy {lambda}

Kotlin array.indexOf(item)但我无法弄明白该怎么做array.indexOfBy { lambda }.它不存在吗?我可以find一个项目,但我不能同时得到它的索引.

我错过了stdlib中的函数吗?

我可以创建一个带有循环的函数,该循环可以解析项目并在找到目标时返回.像这样:

fun <T : Any> indexOfBy(items: Array<T>, predicate: (T) -> Boolean): Int {
    for (i in items.indices) { // or (i in 0..items.size-1)
        if (predicate(items[i])) {
            return i
        }
    }
    return -1
}
Run Code Online (Sandbox Code Playgroud)

然后我尝试使用forEach以下功能使其更具功能性:

fun <T : Any> indexOfBy(items: Array<T>, predicate: (T) -> Boolean): Int {
    (items.indices).forEach {
        if (predicate(items[it])) {
            return it
        }
    }
    return -1
}
Run Code Online (Sandbox Code Playgroud)

或者我可以做一些像这样愚蠢的事情,这不是很有效:

val slowAndSilly = people.indexOf(people.find { it.name == "David" …
Run Code Online (Sandbox Code Playgroud)

kotlin

6
推荐指数
1
解决办法
3110
查看次数

如何在Kotlin中更轻松地使用Jooq交易

我有使用事务在Kotlin中编写的Jooq代码,有时我想要一个独立的方法作为顶级操作,它将拥有自己的事务,有时希望它与同一事务中的其他方法一起工作.例如,我有两个低级函数actionAbcactionXyz我想要撰写成不同的更高级别的数据的方法和继承他们的交易如果存在的话,否则有自己的.

我知道在Spring或其他框架中可以添加一些注释来验证"需要事务"或"如果没有则创建事务"类型功能.但是如何在不使用这些库的情况下对Jooq + Kotlin做同样的事情呢?

我最接近的是将事务作为可选参数传递,如果缺少则将其默认为新事务.但如果有人忘记传递交易,那么使用新的顶级和无关交易会有微妙的失败,我不希望如此.

fun tx(ctx: DSLContext = rootContext, codeBlock: DSLContext.() -> Unit): Unit {
        ctx.transaction { cfg ->
            DSL.using(cfg).codeBlock()
        }
    }
}

// and used as:

fun actionAbc(parm1: String, parm2: Int, ctx: DSLContext = rootContext) {
   tx(ctx) { ... }
}

fun actionXyz(parm: Date, ctx: DSLContext = rootContext) {
   tx(ctx) { ... }
}

// composed:

fun higherLevelAction(parm1: String, parm2: Date) {
  tx {
    actionAbc(parm1, 45, this) // if you forget `this` you are …
Run Code Online (Sandbox Code Playgroud)

transactions jooq kotlin

6
推荐指数
1
解决办法
501
查看次数

在Kotlin中,如何针对不同的设置分支限制流畅的Builder中的选择

在Kotlin,我正在编写一个构建器,并且需要一系列明显且必须完成的步骤.使用流畅的构建器,我可以显示所有步骤,但不能确定它们必须发生的顺序,也不能根据上一步更改哪些步骤可用.所以:

serverBuilder().withHost("localhost")
         .withPort(8080)
         .withContext("/something")
         .build()
Run Code Online (Sandbox Code Playgroud)

很好,但随后添加SSL证书等选项:

serverBuilder().withHost("localhost")
         .withSsl()
         .withKeystore("mystore.kstore")
         .withContext("/secured")
         .build()
Run Code Online (Sandbox Code Playgroud)

现在没有什么能阻止非ssl版本拥有withKeystore和其他选项.在没有首先打开的情况下调用此SSL方法时应该出错withSsl():

serverBuilder().withHost("localhost")
         .withPort(8080)
         .withContext("/something")
         .withKeystore("mystore.kstore")   <------ SHOULD BE ERROR!
         .build()
Run Code Online (Sandbox Code Playgroud)

在路上有更多的叉子可能会更复杂,我只想要一些物品而不是其他物品.

如何限制构建器逻辑中每个分支可用的功能?这对建筑商来说是不可能的,而应该是DSL吗?

注意: 这个问题是由作者故意编写和回答的(答案问题),因此对于常见问题的Kotlin主题的惯用答案存在于SO中.

kotlin

6
推荐指数
1
解决办法
203
查看次数

Kotlin使用Java回调接口

我有一个WebView.我想打电话

public void evaluateJavascript(String script, ValueCallback<String> resultCallback)
Run Code Online (Sandbox Code Playgroud)

这种方法.

这是ValueCallback接口:

public interface ValueCallback<T> {
    /**
     * Invoked when the value is available.
     * @param value The value.
     */
    public void onReceiveValue(T value);
};
Run Code Online (Sandbox Code Playgroud)

这是我的kotlin代码:

webView.evaluateJavascript("a", ValueCallback<String> {
            // cant override function
        })
Run Code Online (Sandbox Code Playgroud)

有人想知道在kotlin中覆盖onReceiveValue方法吗?我尝试了"将Java转换为Kotlin",但结果是下一个:

v.evaluateJavascript("e") {  }
Run Code Online (Sandbox Code Playgroud)

谢谢!

kotlin kotlin-interop

6
推荐指数
2
解决办法
6236
查看次数

无法让Dokka在Gradle / Android项目上生成Kotlin文档

我正在关注https://github.com/Kotlin/dokka中的gradle插件部分。

我还在https://github.com/JetBrains/kotlin-examples/tree/master/gradle/dokka-gradle-example中尝试了dokka-gradle-example示例。

我使用的版本是:

android: '23.1.1'
dokka: '0.9.6'
gradle-android-plugin: '1.5.0'
kotlin: '1.0.0-rc-1036'
Run Code Online (Sandbox Code Playgroud)

但我也尝试使用0.9到0.9.7之间的Dokka版本。

输出的相关部分是:

...

:app:dokka FAILED
:app:dokka (Thread[Daemon worker Thread 9,5,main]) completed. Took 0.766 secs.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:dokka'.
> com.intellij.mock.MockComponentManager.getPicoContainer()Lorg/picocontainer/MutablePicoContainer;

* Try:
Run with --debug option to get more log output.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:dokka'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:64)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:42)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52) …
Run Code Online (Sandbox Code Playgroud)

android gradle kotlin kotlin-dokka

5
推荐指数
1
解决办法
2042
查看次数

我有一个Vertx请求,我需要计算一个外部可见(公共)URL

我将Kotlin与Vertx 3结合使用,有时我需要从公共URL的角度返回特定的URI,这与Vertx-Web请求认为我的URL的URL不同。这可能是由于我的负载均衡器或代理接收了一个URL,然后通过内部URL转发到我的应用程序。

因此,如果我这样做:

val publicUrl = context.request().absoluteURI() 
Run Code Online (Sandbox Code Playgroud)

我最终得到一个URL http://10.10.103.22:8080/some/page而不是https://app.mydomain.com/some/page。该网址的所有内容都不对!

我发现了一个头,理应告诉我更多的原始请求,如X-Forwarded-Host但只包括app.mydomain.com或有时它的端口app.mydomain:80,但是这是不够找出网址的各个部分,我结束了像http://app.mydomain.com:8080/some/page这仍然是不正确的公共URL。

我还不仅需要处理我的当前URL,还需要处理对等URL,例如在同一服务器上的页面“ something / page1”上转到“ something / page2”。由于无法获得公共URL的重要部分,因此当我尝试解析为另一个URL时也提到了相同的问题。

我找不到Vertx-web中的方法来确定此公共URL,还是一些惯用的方法来解决此问题?

我使用Kotlin进行编码,因此该语言的任何示例都很棒!

注意: 这个问题是作者故意写和回答的(自我回答的问题),因此,有趣的问题的解决方案在SO中共享。

kotlin vert.x

5
推荐指数
1
解决办法
570
查看次数

使用GSON进行Kotlin对象反序列化

我上课了

class ThreadComment(
    banned: Int,
    closed: Int,
    comment: String?,
    date: String?,
    email: String?,
    files: ArrayList<File>?,
    lasthit: Int,
    name: String?,
    num: String?,
    op: Int,
    parent: String?,
    postsCount: Int,
    sticky: Int,
    subject: String?,
    tags: String?,
    timestamp: Int,
    trip: String?) : Comment(banned, closed, comment, date, email, files, lasthit, name, num, op, parent, postsCount, sticky, subject, tags, timestamp, trip) {

val answers: ArrayList<String> = ArrayList()}
Run Code Online (Sandbox Code Playgroud)

父类看起来像

open class Comment(
    @com.google.gson.annotations.SerializedName("banned")
    val banned: Int = 0,

    @com.google.gson.annotations.SerializedName("closed")
    val closed: Int = 0,

    @com.google.gson.annotations.SerializedName("comment")
    val comment: …
Run Code Online (Sandbox Code Playgroud)

gson kotlin

5
推荐指数
2
解决办法
8804
查看次数

使用 Amazon AWS Cognito `.wellknown/jwks.json` 数据无法对某些字段进行 Base64 解码

使用 Amazon AWS Cognito Federated Identities并解析以下位置的数据时:
https://cognito-identity.amazonaws.com/.well-known/jwks_uri如下所示:

{"keys":[
    {"kty":"RSA",
     "alg":"RS512",
     "use":"sig",
     "kid":"ap-northeast-11",
     "n":"AI7mc1assO5n6yB4b7jPCFgVLYPSnwt4qp2BhJVAmlXRntRZ5w4910oKNZDOr4fe/BWOI2Z7upUTE/ICXdqirEkjiPbBN/duVy5YcHsQ5+GrxQ/UbytNVN/NsFhdG8W31lsE4dnrGds5cSshLaohyU/aChgaIMbmtU0NSWQ+jwrW8q1PTvnThVQbpte59a0dAwLeOCfrx6kVvs0Y7fX7NXBbFxe8yL+JR3SMJvxBFuYC+/om5EIRIlRexjWpNu7gJnaFFwbxCBNwFHahcg5gdtSkCHJy8Gj78rsgrkEbgoHk29pk8jUzo/O/GuSDGw8qXb6w0R1+UsXPYACOXM8C8+E=",
     "e":"AQAB"}, 
 ... }
Run Code Online (Sandbox Code Playgroud)

n使用以下代码(Kotlin 调用 JDK 8 Base64 类)可以很好地解码字段:

Base64.getDecoder().decode(encodedN.toByteArray())
Run Code Online (Sandbox Code Playgroud)

但是,当使用 Cognito用户池时,其 URL 中的数据格式如下:
https://cognito-idp.${REGION}.amazonaws.com/${POOLID}/.well-known/jwks.json

它具有相同类型的数据,但不会解码。相反,我最终会遇到以下错误:

非法的 base64 字符 5f

由于这是一个下划线_并且在Base64 URL字母表中,我尝试将解码更改为:

Base64.getUrlDecoder().decode(encodedN.toByteArray())
Run Code Online (Sandbox Code Playgroud)

但随后第一组数据将不再正确解码,因为它包含Base64 URL/编码的其他无效字符。

有没有一种方法可以使用jwks同一个解码器处理这两组数据?!?

注: 这个问题是作者特意写出来并回答的(自答问题),以便在SO中分享有趣问题的解决方案。

java amazon-web-services kotlin amazon-cognito

5
推荐指数
1
解决办法
2214
查看次数