kotlin.String!类型的含义是什么?我怎样才能编译下面的代码?

fun withDefault<A>(computation: () -> A, default: A) =
    try { computation() } catch (e: Exception) { default }

fun getHostname1() = withDefault(InetAddress.getLocalHost().getCanonicalHostName, "localhost")

编译器将打印以下错误消息:

Kotlin: Type inference failed: fun <A> withDefault(computation: () -> A, default: A): A
cannot be applied to
(kotlin.String!,kotlin.String)

推荐答案

When the type ends with ! it means that this is a platform type and compiler does not enforce null-safety for it. You can read about platform types in official blog, section Platform Types.

I suggest such fix:

fun getHostname1() = withDefault({ InetAddress.getLocalHost().getCanonicalHostName() } , "localhost")

Kotlin相关问答推荐

在KMP中使用koin将来自Android的上下文注入到SQLDelight Driver中

在Kotlin中,有没有一种函数方法将一个列表(N个元素)映射到一个相邻元素之和列表(N—1个元素)?

Kotlin:将泛型添加到列表任何>

用A*搜索算法解决特修斯和米诺陶尔难题

从 Kotlin 的父类获取函数注解

try 一次性插入多条记录时,JOOQ连接为空错误

如何在数据类中删除空格 (String)?

在 kotlin 原始字符串中转义三重引号

Kotlin:我可以将函数分配给 main 的伴随对象中的变量吗?

在 Kotlin 协程中切换 IO 和 UI 的正确方法是什么?

高效匹配两个 Flux

Kotlin 从其他类调用成员扩展函数

Kotlin - 当表达式返回函数类型

Kotlin 插件错误:无法为类 org.jetbrains.kotlin.gradle.tasks.KotlinCompile 生成代理类

主机名不能为空

Kotlin:什么是 kotlin.String!类型

如何将vararg转换为list?

Kotlin 与 C# 中的标志枚举变量具有相似效果的方式是什么

比较Kotlin的NaN

如何在 firebase 数据库中使用 kotlin 协程