There is a model for kotlin :

 import android.arch.lifecycle.ViewModel class TestModel<V : TestView> : ViewModel() { fun attach(view: V) { Log.d("testLog", "TestModel - attach() = $view") } } 

Interface:

 interface TestView { fun showError() } 

There is an Activity using it on java :

 import android.arch.lifecycle.ViewModelProviders; public class TestActivity extends AppCompatActivity implements TestView { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); TestModel model = ViewModelProviders.of(this).get(TestModel.class); model.attach(this); } @Override public void showError() {} } 

The code is working. How to convert TestActivity to kotlin ? I also tried to use the built-in converter in Android Studio , I failed.

  • If the converter fails, then how else, with pens :) And carefully in ViewModel , no references to activations! There will be memory leaks. - Eugene Krivenja
  • @Eugene Pens and try) I know about the account of links to activations, so I am passing the view, but I will recheck more. Thank. - iamtihonov
  • @EugeneKrivenja replied. The first time did not refer correctly. - iamtihonov

1 answer 1

 import android.arch.lifecycle.ViewModelProviders public class TestActivity : AppCompatActivity, TestView { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val model = ViewModelProviders.of(this).get(TestModel::class.java) model.attach(this) } override fun showError() {} } 

You also need to specify the type that the attach method will work with:

 fun <V> attach(par: V) { } 

Or so in the activation:

 val model = ViewModelProviders.of(this).get<TestModel<*>>(TestModel::class.java) as TestModel<TestView> model.attach(this) import android.arch.lifecycle.ViewModelProviders public class TestActivity : AppCompatActivity, TestView { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val model = ViewModelProviders.of(this).get(TestModel::class.java) as TestModel<TestView> model.attach(this) } override fun showError() {} } 

And so in TestModel:

 class TestModel<V : TestView> : ViewModel() { private lateinit var view : V fun attach(par: V) { view = par Log.d("testLog", "TestModel - attach() = $view") } } 
  • one
    semicolons can be removed) - yno7
  • @ yno7, really) - YurySPb
  • @Yuriy SPb tried this way too, the error gradle falls out: TestActivity.kt: (15, 15): Out-projected type 'TestModel <*>' public 'fun (par: V): Unit defined in *. TestModel ': app: compileDebugKotlin FAILED - iamtihonov
  • @iamtihonov, and you can give a link to the repository with an example for playback? - Yuriy SPb
  • @Yurii SPb github.com/iamtihonov/TestGeneric - iamtihonov