本文介绍了Kotlin:什么是kotlin.String!类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Kotlin的新手.您能解释一下"kotlin.String"是什么意思吗?类型以及如何使以下代码进行编译?
I am new to Kotlin. Could you explain me what is the meaning of the "kotlin.String!" type and how could I make the following code to compile?
fun withDefault<A>(computation: () -> A, default: A) =
try { computation() } catch (e: Exception) { default }
fun getHostname1() = withDefault(InetAddress.getLocalHost().getCanonicalHostName, "localhost")
编译器将显示以下消息:
The compiler prints the following message:
Kotlin: Type inference failed: fun <A> withDefault(computation: () -> A, default: A): A
cannot be applied to
(kotlin.String!,kotlin.String)
谢谢.
推荐答案
当类型以!
结尾时,表示这是平台类型,并且编译器不对其强制执行null安全性.您可以在官方博客部分Platform Types
.
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:什么是kotlin.String!类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!