https://kotlinlang.org logo
a

aaverin

04/07/2020, 1:39 PM
is it possible to use extension functions in
when
statements?
Copy code
when(myObject) {
  myCustomExtensionFunctionOnMyObject -> do something
}
m

Milan Hruban

04/07/2020, 1:49 PM
I believe you would have to use
when
expression without a subject (assuming the extension returns boolean)
Copy code
val myObject = ...

when {
myObject.myCustomExtensionFunctionOnMyObject() -> do something
}
a

aaverin

04/07/2020, 1:50 PM
hmm, then multiple cases do not combine
like
Copy code
when {
  myObject.check1() -> do1
  myObject.check2(),
  myObject.check3() -> do23
  else -> doElse
}
Maybe && will work
or ||
👍 1
m

Milan Hruban

04/07/2020, 1:51 PM
yes it will, but I think you meant ||
j

jaqxues

04/07/2020, 2:15 PM
you can also define a val in when:
Copy code
when (val myObj = someProp.getSth()) {
    myObj.test1() -> //...
    myObj.test2() -> //...
}
might be handy for some use cases
👍 1
he wants to use it with a when
d

David Eriksson

04/07/2020, 2:24 PM
Silly me, thanks @jaqxues