0

Code snippets are from the Scala REPL.

This is perfectly legal Scala even though it is not very useful:

scala> class Test {
  private val xs = scala.collection.mutable.ArrayBuffer[Int]()
  private val func = Some((x: Int)=>{
  })
  private var opt: Option[(Int)=>Unit] = None
  opt = func
}
defined class Test

However, if I try to do something inside func the code will not compile:

scala> class Test {
  private val xs = scala.collection.mutable.ArrayBuffer[Int]()
  private val func = Some((x: Int)=>{
    xs += x
  })
  private var opt: Option[(Int)=>Unit] = None
  opt = func
}
<console>:13: error: type mismatch;
 found   : Some[Int => Test.this.xs.type]
 required: Option[Int => Unit]
         opt = func
               ^

Instead it produces the type mismatch error and lists the types found and required. While this error message is useful, I don't know how to fix it. My next attempt was this:

scala> class Test {
  private val xs = scala.collection.mutable.ArrayBuffer[Int]()
  private val func = Some((x: Int)=>{
    xs += x
    Unit
  })
  private var opt: Option[(Int)=>Unit] = None
  opt = func
}
<console>:14: error: type mismatch;
 found   : Some[Int => Unit.type]
 required: Option[Int => Unit]
         opt = func
               ^

I understand that there is a type mismatch occurring, but I don't understand why there is a type mismatch or how to fix it in such a way that I can do something useful inside func.

Why is there a type mismatch and how can it be fixed?

1 Answer 1

3

Function inside options uses mutable array buffer and returns it as a result, but you need Unit, you can do it this way:

private val func = Some((x: Int)=> {xs += x; ()})

or use append which return type is Unit

private val func = Some((x: Int) => xs.append(x))
6
  • So it looks like I was on the right track when I tried to specify Unit as the last line of the function. What is the difference between Unit and ()?
    – axiopisty
    Dec 3, 2014 at 4:05
  • It's the same basically, new Unit == () == "java void" Dec 3, 2014 at 4:07
  • 1
    Just "Unit" - it's the name of the type, and '()' instance of type Unit, so that's why you had problems with last try Dec 3, 2014 at 4:08
  • 1
    but Unit is a special type, so it's not "real instance of Unit type", for type system it feels like an instance Dec 3, 2014 at 4:09
  • 1
    Well actually what happens is that the Unit type has a companion object (whose name is thus also Unit, and whose type is Unit.type). In axiopisty's code it is that latter that was returned (when (s)he should have returned ()). It's no different than trying to return Int in a function with return type Int (this will return the Int companion, typed as Int.type) instead of returning say 123 . Dec 3, 2014 at 8:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.