【Kotlin】バッキング・フィールド/プロパティ

フィールド

Fields cannot be declared directly in Kotlin classes.
Kotlin クラスでは、直接にフィールドを宣言することはできません。

プロパティ


// Kotlin
class Human {
    val age = 20
}


// Java
public final class Human {
   private final int age = 20;

   public final int getAge() {
      return this.age;
   }
}

バッキング・フィールド

ゲッターやセッターにカスタムロジックを入れたい場合は、「バッキング・フィールド」を使うことができます。

カスタムゲッターやセッターのスコープ内で「field」にアクセスできます。


// Kotlin
var counter = 0
    set(value) {
        if (value >= 0) field = value
    }


// Kotlin
class Human {
    val age = 20
        get() {
            println("Age is: $field")
            return field
        }
}


// Java
public final class Human {
   private final int age = 20;

   public final int getAge() {
      String var1 = "Age is: " + this.age;
      System.out.println(var1);
      return this.age;
   }
}

バッキング・プロパティ

ゲッターやセッターの外でフィールドに直接アクセスしたいときなどに使います。

private なフィールドに_を付けて明示します。


// Kotlin
private var _table: Map<String, Int>? = null
public val table: Map<String, Int>
    get() {
        if (_table == null) {
            _table = HashMap() // Type parameters are inferred
        }
        return _table ?: throw AssertionError("Set to null by another thread")
    }


// Kotlin
class Human {
    private val _age: Int = 20
    val age: Int
        get() {
            return _age
        }

     val printAge = {
         println("Age is: $_age")
     }
}


// Java
public final class Human {
   private final int _age = 20;
   @NotNull
   private final Function0 printAge = (Function0)(new Function0() {
      public Object invoke() {
         this.invoke();
         return Unit.INSTANCE;
      }

      public final void invoke() {
         String var1 = "Age is: " + Human.this._age;
         System.out.println(var1);
      }
   });

   public final int getAge() {
      return this._age;
   }

   @NotNull
   public final Function0 getPrintAge() {
      return this.printAge;
   }
}

まとめ

Java にデコンパイルした状況を確認しながら進むと理解しやすいように思います。

👉【Kotlin】Properties and Fields: Getters, Setters
👉 Properties and Fields: Getters, Setters, const, lateinit - Kotlin Programming Language
👉 Backing properties in Kotlin – ProAndroidDev
👉【MVVM】 ViewModel の_プロパティ記述


Kotlin で書きたい「正しいシングルトン(Singleton)」

汎用性のある使えるシングルトン、

どのように書いてますか?


class Singleton private constructor() {

  // getInstance() ???

}

ここから、どんな getInstance() を?

いくつか。


fun getInstance(): Singleton {
  synchronized(this) {
    if(INSTANCE == null){
      INSTANCE = Singleton()
    }
    return INSTANCE!!
  }
}


companion object {
  private var INSTANCE: Singleton ? = null
  fun getInstance(): Singleton {
    if(INSTANCE == null){
      INSTANCE = Singleton()
    }
    return INSTANCE!!
  }
}


companion object {
  val INSTANCE = Singleton()
  fun  getInstance(): Singleton {
    return INSTANCE
  }
}


@Volatile private var INSTANCE: Singleton ? = null
fun getInstance(): Singleton {
  if(INSTANCE == null){
    synchronized(this) {
      INSTANCE = Singleton()
    }
  }
  return INSTANCE!!
}


companion object {
  @Volatile private var INSTANCE: Singleton ? = null
  fun getInstance(): Singleton {
    return INSTANCE?: synchronized(this){
      Singleton().also {
        INSTANCE = it
      }
    }
  }
}

Singleton Pattern — What you might be doing wrong! – Hacker Noon

正解?

Googleの人はこう書いてます。


class CheeseRepository(
  private val api: CheeseApi,
  private val db: CheeseDatabase,
  private val executor: Executor
) {

  companion object {
    private const val PAGE_SIZE = 30

    private var instance: CheeseRepository? = null

    fun getInstance(context: Context) = instance ?: synchronized(this) {
      instance ?: CheeseRepository(
          CheeseApi(),
          Room.databaseBuilder(context, CheeseDatabase::class.java, "cheese").build(),
          Executors.newFixedThreadPool(4)
      ).also { instance = it }
    }
  }

CheesePage/CheeseRepository.kt at master · yaraki/CheesePage

あと、Dagger の @Singleton もこのスタイルに変換されますので安心です。覚えておきたい記述です。

まとめ

なんだか気持ちが悪くても、
なかなか正解が見つけられないこと多くね? 最近。


Paging DataSourceFactory toLiveData() toObservable() が見つからない。

Javaのこのコードが、


public class ConcertViewModel extends ViewModel {
  private ConcertDao concertDao;
  public final Observable<PagedList<Concert>> concertList;

  public ConcertViewModel(ConcertDao concertDao) {
    this.concertDao = concertDao;
    concertList = new RxPagedListBuilder<>(
          concertDao.concertsByDate(), 50)
                  .buildObservable();
  }
}

Kotlinでこう書けるはずなのに!


class ConcertViewModel(concertDao: ConcertDao) : ViewModel() {
  val concertList: Observable<PagedList<Concert>> =
        concertDao.concertsByDate().toObservable(pageSize = 50)
}

Paging library overview  |  Android Developers

見つからない toObservable()。

- Added DataSourceFactory.toLiveData() as a Kotlin alternative for LivePagedListBuilder
- Added DataSourceFactory.toObservable() and toFlowable() as Kotlin alternatives for RxPagedListBuilder

Paging  |  Android Developers

どうやら -ktx のようです。


implementation "androidx.paging:paging-runtime-ktx:2.1.0"
implementation "androidx.paging:paging-rxjava2-ktx:2.1.0"

Maven Repository: androidx.paging

最近は、同じ処理でも複数の書き方があることが多くなって最初混乱したりします。