Kotlin: What is kotlin.String! type

2019-04-27 02:59发布

问题:

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)

Thank You.

回答1:

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