Live templates allow you to quickly add text to the current file. They are context aware so that only relevant templates for the current cursor location are shown.
You can insert the template into your file by writing the templates name, or by pressing ⌘+j to bring up the live template context menu, the you can search for the template by name.
How to add?
- Copy the template from below
- Go to preferences (⌘+,) > Editor > Live Templates.
- Select the
Kotlin
section. - Paste
- :moneybag:
Result block for service call
Use this within the completion block on a service call that takes a Result.
<template name="serresult" value="result -> result.success?.let { } result.failure?.let { }" description="service results block" toReformat="true" toShortenFQNames="true">
<context>
<option name="KOTLIN_EXPRESSION" value="true" />
</context>
</template>
Example output
result ->
result.success?.let {
}
result.failure?.let {
}
Mock var for unit test
<template name="mock" value="@Mock lateinit var $NAME$: $TYPE$" description="Mock var" toReformat="false" toShortenFQNames="true">
<variable name="NAME" expression="" defaultValue="" alwaysStopAt="true" />
<variable name="TYPE" expression="" defaultValue="" alwaysStopAt="true" />
<context>
<option name="KOTLIN_CLASS" value="true" />
</context>
</template>
Example output
@Mock
lateinit var <name>: <type>
Where <name>
and <type>
are replaced on template insertion
Run with mock annotation
<template name="runwithmock" value="@RunWith(MockitoJUnitRunner::class)" description="Run With Mock annotation" toReformat="false" toShortenFQNames="true">
<context>
<option name="KOTLIN_TOPLEVEL" value="true" />
</context>
</template>
Example
Adds @RunWith(MockitoJUnitRunner::class)
to a class
Test function
<template name="testfun" value="@Test fun test_$NAME$() { // Given $END$ // When // Then } " description="Test function" toReformat="true" toShortenFQNames="true">
<variable name="NAME" expression="" defaultValue="" alwaysStopAt="true" />
<context>
<option name="KOTLIN_CLASS" value="true" />
</context>
</template>
Example
@Test
fun test_<name>() {
// Given
<end>
// When
// Then
}
Where <name>
is replaced on template insertion, and <end>
is where the cursor will be placed once
the name has been set (press enter after entering the name).