Reputation: 5146
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?
Upvotes: 0
Views: 3248
Reputation: 9734
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))
Upvotes: 3