在Kotlin的分支条件下使用传递给的参数?

时间:2017-09-02 07:37:45

标签: kotlin

我有一些大致如下的代码:

val myObject = myObjectRepository.findById(myObjectId);    
when {        
    matchesSomething(myObject) -> doSomethingWithMyObject(myObject)
    matchesSomethingElse(myObject) -> doSomethingElseWithMyObject(myObject)
    else -> log.warn("No match, aborting");
}

虽然这有效,但如果我只需要访问myObject范围内的when,我认为以下(不起作用)会有所改进:

when(myObjectRepository.findById(myObjectId)) { myObject ->
    matchesSomething(myObject) -> doSomethingWithMyObject(myObject)
    matchesSomethingElse(myObject) -> doSomethingElseWithMyObject(myObject)
    else -> log.warn("No match, aborting"); 
}

我得到的错误是:

  

未解决的参考:myObject

你能在Kotlin做这样的事情,如果是这样的话怎么样?如果没有,是否有特殊原因导致为什么不允许这样做?

3 个答案:

答案 0 :(得分:2)

the documentation所示,正确的语法是

val myObject = myObjectRepository.findById(myObjectId);
when {
    matchesSomething(myObject) -> doSomethingWithMyObject(myObject)
    matchesSomethingElse(myObject) -> doSomethingElseWithMyObject(myObject)
    else -> log.warn("myObject not found, aborting")
}

或者,要实际匹配第一个代码段的作用:

val myObject = myObjectRepository.findById(myObjectId);
when(myObject) {
    null -> log.warn("myObject not found, aborting");
    matchesSomething(myObject) -> doSomethingWithMyObject(myObject)
    matchesSomethingElse(myObject) -> doSomethingElseWithMyObject(myObject) 
}

答案 1 :(得分:1)

你必须小心语法。在while中,我们使用与lambdas无关的箭头->。我认为这就是你在你的例子中所尝试的。

when唯一有效的语法是:

when (x) {
   1 -> print("x == 1")
   2 -> print("x == 2")
   else -> { // Note the block
       print("x is neither 1 nor 2")
   }

在箭头->的左侧,您声明对象(x)与匹配的对象是什么,而在右侧则告诉您在该情况下将执行的内容。阅读here

在您的示例中,您尝试链接多个不起作用的->

答案 2 :(得分:0)

从Kotlin 1.3开始支持此功能。它被称为“ Capturing when subject in a variable”,看起来像这样(摘自他们的文档):

fun Request.getBody() =
        when (val response = executeRequest()) {
            is Success -> response.body
            is HttpError -> throw HttpException(response.status)
        }