2017-06-07 20 views
1

で直接プロパティを取得(または私は、デリゲート自体に状態を維持してください):設定と私はこのような委任に渡されたプロパティを設定し、取得したいデリゲート

class Example { 
    var p: String by Delegate() 
} 

class Delegate() { 
    operator fun getValue(thisRef: Any?, prop: KProperty<*>): String { 
     if (prop/*.getValueSomehow()*/){ //<=== is this possible 

     } else { 
      prop./*setValueSomehow("foo")*/ 
      return prop./*.getValueSomehow()*/ //<=== is this possible 
     } 
    } 

    operator fun setValue(thisRef: Any?, prop: KProperty<*>, value: String) { 
     prop./*setValueSomehow(someDefaultValue)*/ //<=== is this possible 
    } 
} 

答えて

2

あなたは、いくつかの変更を行いたい場合や、ゲッターとセッターの内部をチェックすると、このようにすることができます

class Example { 
    var p: String by Delegate() 
} 

class Delegate() { 
    var localValue: String? = null 

    operator fun getValue(thisRef: Any?, prop: KProperty<*>): String { 

     //This is not possible. 
//  if (prop/*.getValueSomehow()*/){ //<=== is this possible 
// 
//  } else { 
//   prop./*setValueSomehow("foo")*/ 
//     return prop./*.getValueSomehow()*/ //<=== is this possible 
//  } 

     if(localValue == null) { 
      return "" 
     } else { 
      return localValue!! 
     } 
    } 


    operator fun setValue(thisRef: Any?, prop: KProperty<*>, value: String) { 
     // prop./*setValueSomehow(someDefaultValue)*/ //<=== is this possible - this is not possible 
     localValue = value 
    } 
} 
関連する問題