Fix ObservablePref Scala 2.11 compatibility

Scala 2.11 doesn't automatically lift functions into implementations
of single-method interfaces, so we have to be a bit more explicit when
creating the callback object.
This commit is contained in:
Sarah Gerweck 2017-12-19 23:00:06 -08:00
parent 607711da06
commit f7bd816b79
No known key found for this signature in database
GPG Key ID: AFCB37207DB3F226

View File

@ -1,7 +1,7 @@
package org.gerweck.scalafx.util package org.gerweck.scalafx.util
package prefs package prefs
import java.util.prefs.Preferences import java.util.prefs._
import scalafx.application.Platform.runLater import scalafx.application.Platform.runLater
import scalafx.beans.property.ObjectProperty import scalafx.beans.property.ObjectProperty
@ -10,7 +10,7 @@ import org.gerweck.scala.util.prefs._
/* TODO: take an implicit that will deteremine whether this is an `ObjectProperty` or what */ /* TODO: take an implicit that will deteremine whether this is an `ObjectProperty` or what */
class ObservablePref[A] protected (path: String)(implicit handler: Pref.AccessHandler[A], prefs: Preferences) class ObservablePref[A] protected (path: String)(implicit handler: Pref.AccessHandler[A], prefs: Preferences)
extends Pref[A](path) { extends Pref[A](path) { thisPref =>
lazy val observe: ObjectProperty[A] = { lazy val observe: ObjectProperty[A] = {
val initialValue: A = this() val initialValue: A = this()
@ -23,23 +23,31 @@ class ObservablePref[A] protected (path: String)(implicit handler: Pref.AccessHa
* in a bidirectional bridge. */ * in a bidirectional bridge. */
/* Preferences => Property bridge */ /* Preferences => Property bridge */
prefs.addPreferenceChangeListener { pce =>
if (pce.getKey == path) { /* In Scala 2.12, the callback could just be bare inside `addPreferenceChangeListener`.
runLater { * However, it must be created explicitly since we cross-compile against Scala 2.11. */
val currentValue = this() val changeListener = new PreferenceChangeListener {
if (property.value != currentValue) { def preferenceChange(pce: PreferenceChangeEvent): Unit = {
property.value = currentValue if (pce.getKey == path) {
runLater {
val currentValue = thisPref()
if (property.value != currentValue) {
property.value = currentValue
}
} }
} }
} }
} }
prefs.addPreferenceChangeListener(changeListener)
/* Property => Preferences bridge */ /* Property => Preferences bridge */
property.onChange { (_, _, newV) => property.onChange { (_, _, newV) =>
if (newV != this()) { if (newV != this()) {
this() = newV this() = newV
} }
()
} }
/* Return the bridged property */
property property
} }
} }