函数的Kotlin类型不匹配返回字符串

时间:2018-10-10 21:12:46

标签: function types kotlin uuid

import java.util.UUID

fun UuidGenerator() {
    val id =  UUID.randomUUID().toString();
    return id.replace("-", "")
}

^^^ UuidGenerator.kt

只需尝试构建一个简单的UUI生成器函数,这样我就可以将其导入到一个类中,并使用它生成32个字符的随机字符串,但仍会导致类型不匹配。

enter image description here

3 个答案:

答案 0 :(得分:1)

您需要指定返回对象: String

fun UuidGenerator() : String {
   val id =  UUID.randomUUID().toString()
   return id.replace("-", "")
}

答案 1 :(得分:1)

如评论中所述,如果您想利用Kotlin的类型推断,而不必指定返回类型,则可以将函数定义为单行

fun UuidGenerator() = UUID.randomUUID().toString().replace("-", "")

答案 2 :(得分:0)

Kotlin中的所有函数都返回一个值(这就是为什么在Kotlin中我们将其称为函数而不是方法)。如果未明确声明,则将隐式返回一个返回值Unit。所以你的代码:

fun UuidGenerator() {
    val id =  UUID.randomUUID().toString();
    return id.replace("-", "")
}

可以改写为:

fun UuidGenerator(): Unit {
    val id =  UUID.randomUUID().toString();
    return id.replace("-", "")
    // ^^^--- oops, won't work
    return Unit
}

如果您看一下它的来源,那将很有意义:

/**
 * The type with only one value: the Unit object.
 * This type corresponds to the `void` type in Java.
 */
public object Unit {
    override fun toString() = "kotlin.Unit"
}

这是消除void的聪明技巧。

现在,您真正想要做的就是指定您要返回的String

fun UuidGenerator(): String {
    val id =  UUID.randomUUID().toString();
    return id.replace("-", "")
}