Skip to content

Instantly share code, notes, and snippets.

@yenerm
Last active April 16, 2024 15:51
Show Gist options
  • Save yenerm/166729b135defb28e0fc94e95782b986 to your computer and use it in GitHub Desktop.
Save yenerm/166729b135defb28e0fc94e95782b986 to your computer and use it in GitHub Desktop.
<!-- Copyright 2019 Google LLC.
SPDX-License-Identifier: Apache-2.0 -->
class Person(name: String, lastname: String) {
var name: String by FormatDelegate(name)
var lastname: String by FormatDelegate(lastname)
var updateCount = 0
}
@eecs441staff
Copy link

eecs441staff commented Oct 12, 2020

Hi Murat, thanks for the great article!

I got the example to work only if I call the constructor on FormatDelegate:

   var name: String by FormatDelegate()
   var lastname: String by FormatDelegate()

Or I declare FormatDelegate a singleton object:

object FormatDelegate : ReadWriteProperty<Any?, String> {

instead of (but then formattedString got clobbered):

class FormatDelegate : ReadWriteProperty<Any?, String> {

@yenerm
Copy link
Author

yenerm commented Oct 12, 2020

Hi,
Thanks for reaching out, really appreciate it.
You can use "class FormatDelegate : ReadWriteProperty<Any?, String>" and it should work. Can you share me what type error you are getting?

@yenerm
Copy link
Author

yenerm commented Oct 12, 2020

ahh i see sorry you are correct it should be:
var name: String by FormatDelegate()
var lastname: String by FormatDelegate()

thanks again!!

@dturner
Copy link

dturner commented Feb 15, 2022

The default values of name and lastname aren't written to the members. To fix this FormatDelegate could accept a default value:

class Person(name: String, lastname: String) {
   var name: String by FormatDelegate(name)
   var lastname: String by FormatDelegate(lastname)
   var updateCount = 0
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment