|
![](/i/favi32.png) Pro Android with Kotlin@de android telegram Pro Android with Kotlin Developing Modern Mobilexxiii
Introduction
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btn.setOnClickListener { view ->
val entered = edit.text.toString()
text.text = "You entered '" + entered +
"' and pressed 'Go'"
}
}
}
Looking at the Kotlin code more thoroughly, a couple of observations emerge:
You don’t need the semicolon delimiters. Kotlin checks at line breaks
whether the statement is finished or whether the following line needs to
be included.
You don’t need
public
in front of the class;
public
is standard in Kotlin.
Instead of
extends
, you just write
:
, improving the readability a little bit.
You don’t need to specify
void
as a return type if a function doesn’t
return anything. Kotlin can infer that.
Unfortunately, you cannot write
contentView = s.th.
as suggested
earlier. The Groovy language, for example, allows for that. The reason
why this can’t be done in Kotlin is that the construct
contentView =
s.th.
implies that there must be a class field named
contentView
, which
is not the case. The compiler could check for appropriately named
methods and then allow for that syntax, but the Kotlin developers
decided to impose this restriction and to prohibit the construct if the
field doesn’t exist. The same is true for
setOnClickListener
because a
field called
onClickListener
doesn’t exist either.
Instead of an anonymous inner class, you can use the functional
construct
view -> …
. This is always possible if the addressed class, the
listener in this case, just contains a single method, like
void onClick(
View v )
in the base interface used here. The Kotlin compiler knows that
it must use that particular single method of the listener class.
The
EditText
,
Button
, and
TextView
variables no longer need to be
declared. This is, however, not related to Kotlin but a mechanism
provided by Android Studio. The import
kotlinx.android.synthetic.
main.activity_main.*
brings you those fields automatically, derived
from the resources.
To review, the Kotlin code with 559 characters does the same as the Java code with 861
characters. This is a savings of 35 percent, a percentage you can expect for more complex
classes as well.
Despite the syntax being different from Java, the Kotlin compiler translates its source code to
the same virtual machine bytecode as Java, so Kotlin can use the plethora of Java libraries that
are out there in the wild, and Java developers switching to or also using Kotlin won’t miss them.
|
|
|