-
Notifications
You must be signed in to change notification settings - Fork 13
Выполнен перевод на Kotlin #5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Выполнен перевод на Kotlin #5
Conversation
private var greetings: String? = null | ||
private var name: String? = null | ||
private var textView: TextView? = null |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
если нам известно, что при создании активности эти поля в любом случае будут иметь значение, то можно возпользоваться отложенной инициализацией:
private lateinit var textView: TextView
это позволит нам не указывать начальное значение и обозначать поле non-nullable типом, что в дальнейшем не будет заставлять нас применять !! или ?. для его обработки
name = if (savedInstanceState?.getString(NAME_KEY) != null) { | ||
savedInstanceState.getString(NAME_KEY) | ||
} else { | ||
getString(R.string.anon) | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Если в котлине появляется IF с условием что-то ==/!= null - то скорее всего игнорируется одна из главных фичей котлина)
можно записать это намного лакончинее:
name = savedInstanceState?.getString(NAME_KEY) ?: getString(R.string.anon)
} else { | ||
getString(R.string.anon) | ||
} | ||
textView = findViewById(R.id.textViewHello) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
о findViewById нужно знать, но лучше сразу использовать View Binding, ну или Kotlin Synthetic
val nameFromData = data.getStringExtra(SecondActivity.NAME_KEY) | ||
if (nameFromData != null) { | ||
name = nameFromData | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
опять же, безопасные вызовы позволят нам сделать код лаконичнее и уменьшить обрамляющее условие:
if (requestCode == SecondActivity.GET_NAME_REQUEST_CODE && resultCode == RESULT_OK)
data?.getStringExtra(SecondActivity.NAME_KEY)?.let { name = it }
|
||
override fun onResume() { | ||
super.onResume() | ||
textView!!.text = String.format("%s, %s!", greetings, name) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
вот к чему и приводит отсутствие lateinit у поля в данном случае
использовать !! считается плохой практикой, потому что тогда можно словить NullPointerException, прямо как и в Java
если такая ситуация всё же произошла, то лучше не выполнить ничего, чем уронить всё приложение:
textView?.text = String.format("%s, %s!", greetings, name)
} | ||
|
||
override fun afterTextChanged(editable: Editable) { | ||
button.isEnabled = !TextUtils.isEmpty(editable) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
у библиотеки kotlin есть удобные extension методы для работы со строками:
button.isEnabled = editable.isNotEmpty()
button.isEnabled = !TextUtils.isEmpty(editable) | ||
} | ||
}) | ||
button.setOnClickListener(View.OnClickListener { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
даже сама студия выделила View.OnClickListener серым)
это потому, что View.OnClickListener - это функциональный интерфейс, а значит он может быть заменён на лямбду
button.setOnClickListener { ... }
No description provided.