Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return Unit from a scala function?

Tags:

scala

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)".

like image 389
jbrown Avatar asked May 26 '15 07:05

jbrown


People also ask

How does return work in Scala?

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.

What is the use of Unit in Scala?

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.

What is the Unit type in Scala?

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.


1 Answers

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.

like image 105
goralph Avatar answered Sep 30 '22 15:09

goralph