使用null参数调用方法

时间:2017-06-05 09:34:37

标签: kotlin

在java中,我们可以调用方法aMethod(val1 , val2)

classObject.aMethod(null_if_Val1_NotAvailable,val2) 在Method中,我将检查val1是否为null 我将初始化

如何在Kotlin中做同样的事情。 我试过,但它说Null不能是非null类型的值

3 个答案:

答案 0 :(得分:3)

您可以使用默认值:

Serial

您现在可以使用默认方法,如下所示:

fun aMethod(val1: String = "default value", val2: String)

答案 1 :(得分:3)

以这种方式试试

==> Expected process to exit with [0], but received '1'
==> ---- Begin output of mongo localhost:30158 /tmp/mongo.setup.users.js ----
==> STDOUT: MongoDB shell version v3.4.2
==> connecting to: localhost:30158
==> 2017-06-05T07:39:48.136+0000 W NETWORK  [thread1] Failed to connect to 127.0.0.1:30158, in(checking soc
ket for error after poll), reason: Connection refused
==> 2017-06-05T07:39:48.136+0000 E QUERY    [thread1] Error: couldn't connect to server localhost:30158, co
nnection attempt failed :

根据您的意愿返回类型 来自this peace of code

的参考 在数据类型允许您为null之后

fun printHello(name: String?): Unit { if (name != null) println("Hello ${name}") else println("Hi there!") // `return Unit` or `return` is optional } 。参考kotlin langauge function tutorial

答案 2 :(得分:1)

Kotlin强调无效安全。如果您希望属性/返回类型/参数/局部变量为null,则必须使用this link,方法是在类型的末尾添加问号。

e.g。

DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX", Locale.ENGLISH);
Date date = format.parse(string);

因此,为了使您的代码正常工作,您只需要指定函数Foo foo = null // doesn't compile Foo? foo = null // compiles fun foo(foo: Foo) foo(null) // doesn't compile fun bar(foo: Foo?) bar(null) // compiles fun foo(): Foo = null // doesn't compile fun foo(): Foo? = null // compiles 采用可为空的类型:

aMethod

然而,在kotlin中,不建议在这里使用null。我们有更好的方法来处理您的情况。我们使用默认参数,如nhaarman所建议。

fun aMethod(val1: SomeType?, val2) {
    //...
}
相关问题