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)) 
Sign up to request clarification or add additional context in comments.

6 Comments

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 ()?
It's the same basically, new Unit == () == "java void"
Just "Unit" - it's the name of the type, and '()' instance of type Unit, so that's why you had problems with last try
but Unit is a special type, so it's not "real instance of Unit type", for type system it feels like an instance
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 .
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.