Skip to content

Commit

Permalink
Kotlin 1.9.0 (#3835)
Browse files Browse the repository at this point in the history
Update to Kotlin 1.9.0 and migrate to newer language idioms.

- Remove unnecessary @OptIn for features migrated to mainstream
- Use `data object` where appropriate
- Use new enum `entries` property
  • Loading branch information
Goooler authored Aug 2, 2023
1 parent 5391b5f commit 40bd95d
Show file tree
Hide file tree
Showing 29 changed files with 44 additions and 71 deletions.
4 changes: 1 addition & 3 deletions app/src/main/java/com/keylesspalace/tusky/TabData.kt
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,7 @@ data class TabData(
other as TabData

if (id != other.id) return false
if (arguments != other.arguments) return false

return true
return arguments == other.arguments
}

override fun hashCode() = Objects.hash(id, arguments)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,10 +114,10 @@ public static class Key {
private final TextView cardDescription;
private final TextView cardUrl;
private final PollAdapter pollAdapter;
protected LinearLayout filteredPlaceholder;
protected TextView filteredPlaceholderLabel;
protected Button filteredPlaceholderShowButton;
protected ConstraintLayout statusContainer;
protected final LinearLayout filteredPlaceholder;
protected final TextView filteredPlaceholderLabel;
protected final Button filteredPlaceholderShowButton;
protected final ConstraintLayout statusContainer;

private final NumberFormat numberFormat = NumberFormat.getNumberInstance();
private final AbsoluteTimeFormatter absoluteTimeFormatter = new AbsoluteTimeFormatter();
Expand Down Expand Up @@ -838,9 +838,7 @@ private void setupFilterPlaceholder(StatusViewData.Concrete status, StatusAction
}

filteredPlaceholderLabel.setText(itemView.getContext().getString(R.string.status_filter_placeholder_label_format, matchedFilter.getTitle()));
filteredPlaceholderShowButton.setOnClickListener(view -> {
listener.clearWarningAction(getBindingAdapterPosition());
});
filteredPlaceholderShowButton.setOnClickListener(view -> listener.clearWarningAction(getBindingAdapterPosition()));
}

protected static boolean hasPreviewableAttachment(List<Attachment> attachments) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ import com.keylesspalace.tusky.service.ServiceClient
import com.keylesspalace.tusky.service.StatusToSend
import com.keylesspalace.tusky.util.randomAlphanumericString
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
Expand All @@ -53,7 +52,6 @@ import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject

@OptIn(FlowPreview::class)
class ComposeViewModel @Inject constructor(
private val api: MastodonApi,
private val accountManager: AccountManager,
Expand Down Expand Up @@ -95,7 +93,7 @@ class ComposeViewModel @Inject constructor(
val media: MutableStateFlow<List<QueuedMedia>> = MutableStateFlow(emptyList())
val uploadError = MutableSharedFlow<Throwable>(replay = 0, extraBufferCapacity = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)

lateinit var composeKind: ComposeKind
private lateinit var composeKind: ComposeKind

// Used in ComposeActivity to pass state to result function when cropImage contract inflight
var cropImageItemOld: QueuedMedia? = null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,6 @@ class AddPollOptionsAdapter(
}

private fun validateInput(): Boolean {
if (options.contains("") || options.distinct().size != options.size) {
return false
}

return true
return !(options.contains("") || options.distinct().size != options.size)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ sealed class LoginResult : Parcelable {
data class Err(val errorMessage: String) : LoginResult()

@Parcelize
object Cancel : LoginResult()
data object Cancel : LoginResult()
}

/** Activity to do Oauth process using WebView. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ public static void updateSummaryNotifications(Context context, NotificationManag
int accountId = (int) account.getId();

// Initialise the map with all channel IDs.
for (Notification.Type ty : Notification.Type.values()) {
for (Notification.Type ty : Notification.Type.getEntries()) {
channelGroups.put(getChannelId(account, ty), new ArrayList<>());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ class NotificationsFragment :
val position = adapter.snapshot().indexOfFirst {
it?.statusViewData?.status?.id == (action as StatusAction).statusViewData.id
}
if (position != RecyclerView.NO_POSITION) {
if (position != NO_POSITION) {
adapter.notifyItemChanged(position)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ class NotificationsPagingAdapter(
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val inflater = LayoutInflater.from(parent.context)

return when (NotificationViewKind.values()[viewType]) {
return when (NotificationViewKind.entries[viewType]) {
NotificationViewKind.STATUS -> {
StatusViewHolder(
ItemStatusBinding.inflate(inflater, parent, false),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ import com.keylesspalace.tusky.util.toViewData
import com.keylesspalace.tusky.viewdata.NotificationViewData
import com.keylesspalace.tusky.viewdata.StatusViewData
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
Expand All @@ -70,7 +69,6 @@ import kotlinx.coroutines.rx3.await
import retrofit2.HttpException
import javax.inject.Inject
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.ExperimentalTime

data class UiState(
/** Filtered notification types */
Expand Down Expand Up @@ -103,7 +101,7 @@ sealed class UiAction
/** Actions the user can trigger from the UI. These actions may fail. */
sealed class FallibleUiAction : UiAction() {
/** Clear all notifications */
object ClearNotifications : FallibleUiAction()
data object ClearNotifications : FallibleUiAction()
}

/**
Expand All @@ -129,7 +127,7 @@ sealed class InfallibleUiAction : UiAction() {
// Resets the account's `lastNotificationId`, which can't fail, which is why this is
// infallible. Reloading the data may fail, but that's handled by the paging system /
// adapter refresh logic.
object LoadNewest : InfallibleUiAction()
data object LoadNewest : InfallibleUiAction()
}

/** Actions the user can trigger on an individual notification. These may fail. */
Expand All @@ -146,13 +144,13 @@ sealed class UiSuccess {
// of these three should trigger the UI to refresh.

/** A user was blocked */
object Block : UiSuccess()
data object Block : UiSuccess()

/** A user was muted */
object Mute : UiSuccess()
data object Mute : UiSuccess()

/** A conversation was muted */
object MuteConversation : UiSuccess()
data object MuteConversation : UiSuccess()
}

/** The result of a successful action on a notification */
Expand Down Expand Up @@ -286,7 +284,7 @@ sealed class UiError(
}
}

@OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class, ExperimentalTime::class)
@OptIn(ExperimentalCoroutinesApi::class)
class NotificationsViewModel @Inject constructor(
private val repository: NotificationsRepository,
private val preferences: SharedPreferences,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -516,7 +516,7 @@ class ViewThreadViewModel @Inject constructor(

sealed interface ThreadUiState {
/** The initial load of the detailed status for this thread */
object Loading : ThreadUiState
data object Loading : ThreadUiState

/** Loading the detailed status has completed, now loading ancestors/descendants */
data class LoadingThread(
Expand All @@ -535,7 +535,7 @@ sealed interface ThreadUiState {
) : ThreadUiState

/** Refreshing the thread with a swipe */
object Refreshing : ThreadUiState
data object Refreshing : ThreadUiState
}

enum class RevealButtonState {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,10 @@ class ViewEditsAdapter(
private val absoluteTimeFormatter = AbsoluteTimeFormatter()

/** Size of large text in this theme, in px */
var largeTextSizePx: Float = 0f
private var largeTextSizePx: Float = 0f

/** Size of medium text in this theme, in px */
var mediumTextSizePx: Float = 0f
private var mediumTextSizePx: Float = 0f

override fun onCreateViewHolder(
parent: ViewGroup,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,12 +132,12 @@ class ViewEditsViewModel @Inject constructor(private val api: MastodonApi) : Vie
}

sealed interface EditsUiState {
object Initial : EditsUiState
object Loading : EditsUiState
data object Initial : EditsUiState
data object Loading : EditsUiState

// "Refreshing" state is necessary, otherwise a refresh state transition is Success -> Success,
// and state flows don't emit repeated states, so the UI never updates.
object Refreshing : EditsUiState
data object Refreshing : EditsUiState
class Error(val throwable: Throwable) : EditsUiState
data class Success(
val edits: List<StatusEdit>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,9 +129,7 @@ data class AccountEntity(
other as AccountEntity

if (id == other.id) return true
if (domain == other.domain && accountId == other.accountId) return true

return false
return domain == other.domain && accountId == other.accountId
}

override fun hashCode(): Int {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ package com.keylesspalace.tusky.util
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlin.time.Duration
import kotlin.time.ExperimentalTime
import kotlin.time.TimeMark
import kotlin.time.TimeSource

Expand Down Expand Up @@ -54,7 +53,6 @@ import kotlin.time.TimeSource
* @param timeout Emissions within this duration of the last emission are filtered
* @param timeSource Used to measure elapsed time. Normally only overridden in tests
*/
@OptIn(ExperimentalTime::class)
fun <T> Flow<T>.throttleFirst(
timeout: Duration,
timeSource: TimeSource = TimeSource.Monotonic
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import android.text.TextPaint
import android.text.style.URLSpan
import android.view.View

open class NoUnderlineURLSpan constructor(val url: String) : URLSpan(url) {
open class NoUnderlineURLSpan(val url: String) : URLSpan(url) {

// This should not be necessary. But if you don't do this the [StatusLengthTest] tests
// fail. Without this, accessing the `url` property, or calling `getUrl()` (which should
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ private fun findPattern(string: String, fromIndex: Int): FindCharsResult {
val result = FindCharsResult()
for (i in fromIndex..string.lastIndex) {
val c = string[i]
for (matchType in FoundMatchType.values()) {
for (matchType in FoundMatchType.entries) {
val finder = finders[matchType]
if (finder!!.searchCharacter == c &&
(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ import com.keylesspalace.tusky.util.Resource
import com.keylesspalace.tusky.util.Success
import com.keylesspalace.tusky.util.getServerErrorMessage
import com.keylesspalace.tusky.util.randomAlphanumericString
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.asFlow
Expand Down Expand Up @@ -64,7 +63,6 @@ class EditProfileViewModel @Inject constructor(
val headerData = MutableLiveData<Uri>()
val saveData = MutableLiveData<Resource<Nothing>>()

@OptIn(FlowPreview::class)
val instanceData: Flow<InstanceInfo> = instanceInfoRepo::getInstanceInfo.asFlow()
.shareIn(viewModelScope, SharingStarted.Eagerly, replay = 1)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.gson.Gson
import com.keylesspalace.tusky.entity.Notification
import com.keylesspalace.tusky.network.MastodonApi
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import okhttp3.ResponseBody.Companion.toResponseBody
import org.junit.Assert.assertEquals
Expand All @@ -38,7 +37,6 @@ import retrofit2.Response

@Config(sdk = [28])
@RunWith(AndroidJUnit4::class)
@OptIn(ExperimentalCoroutinesApi::class)
class NotificationsPagingSourceTest {
@Test
fun `load() returns error message on HTTP error`() = runTest {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ import retrofit2.HttpException
import retrofit2.Response

@OptIn(ExperimentalCoroutinesApi::class)
class MainCoroutineRule constructor(private val dispatcher: TestDispatcher = UnconfinedTestDispatcher()) : TestWatcher() {
class MainCoroutineRule(private val dispatcher: TestDispatcher = UnconfinedTestDispatcher()) : TestWatcher() {
override fun starting(description: Description) {
super.starting(description)
Dispatchers.setMain(dispatcher)
Expand All @@ -62,7 +62,6 @@ class MainCoroutineRule constructor(private val dispatcher: TestDispatcher = Unc

@Config(sdk = [28])
@RunWith(AndroidJUnit4::class)
@OptIn(ExperimentalCoroutinesApi::class)
abstract class NotificationsViewModelTestBase {
protected lateinit var notificationsRepository: NotificationsRepository
protected lateinit var sharedPreferencesMap: MutableMap<String, Boolean>
Expand All @@ -73,7 +72,7 @@ abstract class NotificationsViewModelTestBase {
protected lateinit var viewModel: NotificationsViewModel

/** Empty success response, for API calls that return one */
protected var emptySuccess = Response.success("".toResponseBody())
protected var emptySuccess: Response<ResponseBody> = Response.success("".toResponseBody())

/** Empty error response, for API calls that return one */
protected var emptyError: Response<ResponseBody> = Response.error(404, "".toResponseBody())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ package com.keylesspalace.tusky.components.notifications

import app.cash.turbine.test
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.junit.Test
import org.mockito.kotlin.doReturn
Expand All @@ -34,7 +33,6 @@ import org.mockito.kotlin.verify
* This is only tested in the success case; if it passed there it must also
* have passed in the error case.
*/
@OptIn(ExperimentalCoroutinesApi::class)
class NotificationsViewModelTestClearNotifications : NotificationsViewModelTestBase() {
@Test
fun `clearing notifications succeeds && invalidate the repository`() = runTest {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import app.cash.turbine.test
import com.google.common.truth.Truth.assertThat
import com.keylesspalace.tusky.db.AccountEntity
import com.keylesspalace.tusky.entity.Notification
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.junit.Test
import org.mockito.kotlin.argumentCaptor
Expand All @@ -33,7 +32,6 @@ import org.mockito.kotlin.verify
* - Is the [UiState] updated correctly?
* - Are the correct [AccountManager] functions called, with the correct arguments?
*/
@OptIn(ExperimentalCoroutinesApi::class)
class NotificationsViewModelTestFilter : NotificationsViewModelTestBase() {

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import app.cash.turbine.test
import com.google.common.truth.Truth.assertThat
import com.keylesspalace.tusky.entity.Relationship
import io.reactivex.rxjava3.core.Single
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.junit.Test
import org.mockito.kotlin.any
Expand All @@ -39,7 +38,6 @@ import org.mockito.kotlin.verify
* This is only tested in the success case; if it passed there it must also
* have passed in the error case.
*/
@OptIn(ExperimentalCoroutinesApi::class)
class NotificationsViewModelTestNotificationAction : NotificationsViewModelTestBase() {
/** Dummy relationship */
private val relationship = Relationship(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import at.connyduck.calladapter.networkresult.NetworkResult
import com.google.common.truth.Truth.assertThat
import com.keylesspalace.tusky.FilterV1Test.Companion.mockStatus
import com.keylesspalace.tusky.viewdata.StatusViewData
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.junit.Test
import org.mockito.kotlin.any
Expand All @@ -40,7 +39,6 @@ import org.mockito.kotlin.verify
* This is only tested in the success case; if it passed there it must also
* have passed in the error case.
*/
@OptIn(ExperimentalCoroutinesApi::class)
class NotificationsViewModelTestStatusAction : NotificationsViewModelTestBase() {
private val status = mockStatus(pollOptions = listOf("Choice 1", "Choice 2", "Choice 3"))
private val statusViewData = StatusViewData.Concrete(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import com.keylesspalace.tusky.appstore.PreferenceChangedEvent
import com.keylesspalace.tusky.settings.PrefKeys
import com.keylesspalace.tusky.util.CardViewMode
import com.keylesspalace.tusky.util.StatusDisplayOptions
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.junit.Test

Expand All @@ -34,7 +33,6 @@ import org.junit.Test
* - Does the make() function correctly use an updated preference?
* - Is the correct update emitted when a relevant preference changes?
*/
@OptIn(ExperimentalCoroutinesApi::class)
class NotificationsViewModelTestStatusDisplayOptions : NotificationsViewModelTestBase() {

private val defaultStatusDisplayOptions = StatusDisplayOptions(
Expand Down
Loading

0 comments on commit 40bd95d

Please sign in to comment.