I'm trying to make a function return Unit (this is to implement an RxScala observer), but when I add ()
to the end of it, I get an error "Application does not take parameters". Here's my code:
val client3MessageStreamObserver: Observable[Message] = client3.messageStream()
client3MessageStreamObserver.subscribe(
m => println("Unexpected message received by client3"),
// callback for handling exceptions
t =>
println("Ex client3: " + t)
// want to make this line work (which it doesn't) which is why
// I need to be able to return Unit.
// client3TestPromise.success(true)
() // error after adding Unit literal here.
)
Why do I get this error after adding ()
and how can I get rid of it? If I leave it out I get an error saying "Type mismatch: Expected (Throwable) => Unit, actual: (Throwable) => Any)".
Putting in simple words, return basically transfers the control back to the function. It gives back the result and no statement after the return statement gets executed in that particular function. In scala, the return isn't required to be written with the resultant value.
The Unit is Scala is analogous to the void in Java, which is utilized as a return type of a functions that is used with a function when the stated function does not returns anything.
The Unit type in Scala is used as a return statement for a function when no value is to be returned. Unit type can be e compared to void data type of other programming languages like Java. It is a subclass of anytype trait and is used when nothing means to return by the function.
Try this:
val client3MessageStreamObserver: Observable[Message] = client3.messageStream()
client3MessageStreamObserver.subscribe(
m => println("Unexpected message received by client3"),
t => println("Ex client3: " + t)
() => ()
)
The third function onCompleted
is a function Unit => Unit
. So, the parameter is ()
and then in the return we can explicitly return ()
or any method returning a ()
such as println
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With