val ec = pref.getInt("executionCount", 0)
val editor = pref.edit()
editor.putInt("executionCount", ec + 1)
editor.commit()
Doing some work on the backstage with Type Dynamic, the code can be improved as follows:
val ec = pref.executionCount(0) pref.executionCount = ec + 1
Accessing properties becomes more natural. To do this, I wrote some helper classes using Type Dynamic as shown below:
class IntPreferences(preferences: SharedPreferences) extends Dynamic {
var defaultValue: Int = _
def selectDynamic(name: String): Int =
preferences.getInt(name, defaultValue)
def updateDynamic(name: String)(value: Int) {
preferences.edit().putInt(name, value).commit()
}
}
// Other classes (for Long, Boolean, etc.) are defined as the same way
class Preferences(val preferences: SharedPreferences) extends Dynamic {
def updateDynamic(name: String)(value: Any) {
value match {
case v: String => preferences.edit().putString (name, v).commit()
case v: Int => preferences.edit().putInt (name, v).commit()
case v: Long => preferences.edit().putLong (name, v).commit()
case v: Boolean => preferences.edit().putBoolean(name, v).commit()
case v: Float => preferences.edit().putFloat (name, v).commit()
}
}
val String = new StringPreferences (preferences)
val Int = new IntPreferences (preferences)
val Long = new LongPreferences (preferences)
val Float = new FloatPreferences (preferences)
val Boolean = new BooleanPreferences(preferences)
}
When you access pref.Int.executionCount, Scala compiler expands it to pref.Int.selectDynamic("executionCount"), and pref.executionCount = ec become pref.updateDynamic("executionCount")(ec).The full source code can be found here. You can simply download and enjoy it.
No comments:
Post a Comment