Skip to content

Convert WordAssessmentActivity to Kotlin#54

Merged
tuancoltech merged 6 commits intomainfrom
convert_word_assessmen_to_kotlin
Mar 18, 2025
Merged

Convert WordAssessmentActivity to Kotlin#54
tuancoltech merged 6 commits intomainfrom
convert_word_assessmen_to_kotlin

Conversation

@tuancoltech
Copy link
Copy Markdown
Member

Convert WordAssessmentActivity to Kotlin

@tuancoltech tuancoltech self-assigned this Mar 18, 2025
@tuancoltech tuancoltech requested a review from a team as a code owner March 18, 2025 04:35
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 18, 2025

Walkthrough

This pull request introduces Kotlin enhancements by updating the build configuration and refactoring an activity. The app/build.gradle file now applies the Kotlin Android plugin, specifies Kotlin JVM options with target 17, and adds a dependency on androidx.core.ktx. Additionally, the existing Java-based WordAssessmentActivity has been removed and replaced with a Kotlin implementation that handles UI initialization, word assessment logic, and event logging.

Changes

File(s) Change Summary
app/build.gradle Added Kotlin Android plugin, defined kotlinOptions { jvmTarget = '17' }, and added the androidx.core.ktx dependency.
app/src/.../assessment/WordAssessmentActivity.java and
app/src/.../assessment/WordAssessmentActivity.kt
Removed the Java-based WordAssessmentActivity and added a new Kotlin version to manage word assessment, UI setup, and event logging.
build.gradle Added classpath libs.kotlin.gradle.plugin to the buildscript section for Kotlin Gradle plugin integration.

Possibly related PRs

Suggested reviewers

  • jo-elimu

Poem

I’m a rabbit in a code-filled glen,
Hopping through plugins and gradle den,
Java steps aside, Kotlin takes the lead,
Assessing words with a rhythmic speed,
With every change, I joyfully spin—
Hoppy coding, let the fun begin!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7c365d6 and de8e675.

📒 Files selected for processing (1)
  • app/build.gradle (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • app/build.gradle
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build (windows-latest, 21)
  • GitHub Check: build (windows-latest, 17)
  • GitHub Check: build (macos-latest, 17)
  • GitHub Check: build (macos-latest, 21)
  • GitHub Check: build (ubuntu-latest, 17)
  • GitHub Check: build (ubuntu-latest, 21)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@tuancoltech tuancoltech marked this pull request as draft March 18, 2025 04:35
@tuancoltech tuancoltech marked this pull request as ready for review March 18, 2025 04:39
@tuancoltech tuancoltech requested a review from jo-elimu March 18, 2025 04:39
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (7)
app/src/main/java/ai/elimu/kukariri/assessment/WordAssessmentActivity.kt (7)

23-40: Consider using lateinit instead of nullable types for views

The UI components are currently defined as nullable types with initialization deferred to onCreate. For views that are guaranteed to be initialized before use, Kotlin's lateinit modifier would be more idiomatic and eliminate the need for null-safety operators.

-    private var progressBar: ProgressBar? = null
-    private var textView: TextView? = null
-    private var difficultButton: Button? = null
-    private var easyButton: Button? = null
+    private lateinit var progressBar: ProgressBar
+    private lateinit var textView: TextView
+    private lateinit var difficultButton: Button
+    private lateinit var easyButton: Button

Also, for the collections, consider using Kotlin's collection factory functions:

-    private val wordGsonsPendingReview: MutableList<WordGson> = ArrayList()
-    private val wordGsonsMastered: MutableList<WordGson> = ArrayList()
+    private val wordGsonsPendingReview: MutableList<WordGson> = mutableListOf()
+    private val wordGsonsMastered: MutableList<WordGson> = mutableListOf()

86-91: Simplify word type filtering with Kotlin's 'in' operator

The multi-line conditional check for word types could be simplified using Kotlin's in operator with a set of word types.

-                if ((wordGson.wordType == WordType.ADJECTIVE)
-                    || (wordGson.wordType == WordType.NOUN)
-                    || (wordGson.wordType == WordType.VERB)
-                ) {
+                if (wordGson.wordType in setOf(WordType.ADJECTIVE, WordType.NOUN, WordType.VERB)) {
                     wordGsonsPendingReview.add(wordGson)
                 }

117-118: Use property assignment instead of setter method for duration

In Kotlin, you can directly assign values to properties rather than using setter methods.

-        objectAnimator.setDuration(1000)
+        objectAnimator.duration = 1000

122-125: Eliminate null assertion operators with lateinit

If you change the TextView to use lateinit as suggested earlier, you can remove the null assertion operators (!!) which improves code safety.

-        textView!!.text = wordGson.text
         val appearAnimation =
             AnimationUtils.loadAnimation(applicationContext, R.anim.anim_appear_right)
-        textView!!.startAnimation(appearAnimation)
+        textView.text = wordGson.text
+        textView.startAnimation(appearAnimation)

133-136: Use string templates and safer null handling

Kotlin offers string templates for more readable string concatenation, and you can use safe call operators to handle potential null values.

-            textView!!.text = textView!!.text.toString() + "\n"
-            for (emojiGson in emojiGsons) {
-                textView!!.text = textView!!.text.toString() + emojiGson.glyph
-            }
+            textView.text = "${textView.text}\n"
+            for (emojiGson in emojiGsons) {
+                textView.text = "${textView.text}${emojiGson.glyph}"
+            }

141-157: Replace anonymous inner class with lambda expression

Kotlin allows for more concise click listeners using lambda expressions instead of anonymous inner classes.

-        difficultButton!!.setOnClickListener(object : View.OnClickListener {
-            override fun onClick(v: View) {
-                Log.i(javaClass.name, "difficultButton onClick")
-
-                // Move the Word to the end of the list
-                wordGsonsPendingReview.remove(wordGson)
-                wordGsonsPendingReview.add(wordGson)
-
-                // Report assessment event to the Analytics application (https://github.com/elimu-ai/analytics)
-                AssessmentEventUtil.reportWordAssessmentEvent(
-                    wordGson, 0.00f, System.currentTimeMillis() - timeStart,
-                    applicationContext, BuildConfig.ANALYTICS_APPLICATION_ID
-                )
-
-                loadNextWord()
-            }
-        })
+        difficultButton.setOnClickListener {
+            Log.i(javaClass.name, "difficultButton onClick")
+
+            // Move the Word to the end of the list
+            wordGsonsPendingReview.remove(wordGson)
+            wordGsonsPendingReview.add(wordGson)
+
+            // Report assessment event to the Analytics application (https://github.com/elimu-ai/analytics)
+            AssessmentEventUtil.reportWordAssessmentEvent(
+                wordGson, 0.00f, System.currentTimeMillis() - timeStart,
+                applicationContext, BuildConfig.ANALYTICS_APPLICATION_ID
+            )
+
+            loadNextWord()
+        }

159-175: Replace anonymous inner class with lambda expression

Similar to the previous comment, this click listener can also be simplified with a lambda expression.

-        easyButton!!.setOnClickListener(object : View.OnClickListener {
-            override fun onClick(v: View) {
-                Log.i(javaClass.name, "easyButton onClick")
-
-                // Remove the Word from the list of Words to be repeated, and add it to the list of mastered Words
-                wordGsonsPendingReview.remove(wordGson)
-                wordGsonsMastered.add(wordGson)
-
-                // Report assessment event to the Analytics application (https://github.com/elimu-ai/analytics)
-                AssessmentEventUtil.reportWordAssessmentEvent(
-                    wordGson, 1.00f, System.currentTimeMillis() - timeStart,
-                    applicationContext, BuildConfig.ANALYTICS_APPLICATION_ID
-                )
-
-                loadNextWord()
-            }
-        })
+        easyButton.setOnClickListener {
+            Log.i(javaClass.name, "easyButton onClick")
+
+            // Remove the Word from the list of Words to be repeated, and add it to the list of mastered Words
+            wordGsonsPendingReview.remove(wordGson)
+            wordGsonsMastered.add(wordGson)
+
+            // Report assessment event to the Analytics application (https://github.com/elimu-ai/analytics)
+            AssessmentEventUtil.reportWordAssessmentEvent(
+                wordGson, 1.00f, System.currentTimeMillis() - timeStart,
+                applicationContext, BuildConfig.ANALYTICS_APPLICATION_ID
+            )
+
+            loadNextWord()
+        }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7eae112 and 6ece874.

⛔ Files ignored due to path filters (1)
  • gradle/libs.versions.toml is excluded by !**/*.toml
📒 Files selected for processing (3)
  • app/build.gradle (3 hunks)
  • app/src/main/java/ai/elimu/kukariri/assessment/WordAssessmentActivity.java (0 hunks)
  • app/src/main/java/ai/elimu/kukariri/assessment/WordAssessmentActivity.kt (1 hunks)
💤 Files with no reviewable changes (1)
  • app/src/main/java/ai/elimu/kukariri/assessment/WordAssessmentActivity.java
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build (windows-latest, 17)
  • GitHub Check: build (macos-latest, 21)
  • GitHub Check: build (ubuntu-latest, 17)
  • GitHub Check: build (windows-latest, 21)
  • GitHub Check: build (ubuntu-latest, 21)
  • GitHub Check: build (macos-latest, 17)
🔇 Additional comments (4)
app/build.gradle (3)

1-3: Well-structured Kotlin Android plugin integration

The addition of the Kotlin Android plugin is correctly implemented using the version catalog approach, which is a modern best practice for managing plugin versions in Gradle.


50-52: Appropriate Kotlin JVM target configuration

The kotlinOptions block correctly sets the JVM target to '17', which matches the Java source compatibility defined in the compileOptions block. This ensures consistent bytecode generation across Java and Kotlin sources.


70-70: Good addition of androidx.core.ktx dependency

The androidx.core.ktx library provides Kotlin extensions for AndroidX components, making Android development with Kotlin more concise and idiomatic. This is an essential dependency for Kotlin Android projects.

app/src/main/java/ai/elimu/kukariri/assessment/WordAssessmentActivity.kt (1)

1-177: Successfully converted Java activity to Kotlin with functional equivalence

The WordAssessmentActivity has been successfully converted from Java to Kotlin while maintaining the same functionality. The code handles word assessment logic, UI interactions, and event logging appropriately.

While there are suggestions for making the code more idiomatic Kotlin (as noted in other comments), the current implementation is functionally correct and follows the basic principles of Kotlin programming.

@tuancoltech tuancoltech marked this pull request as draft March 18, 2025 04:42
@tuancoltech tuancoltech marked this pull request as ready for review March 18, 2025 06:05
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2fa828c and 28adbc1.

⛔ Files ignored due to path filters (1)
  • gradle/libs.versions.toml is excluded by !**/*.toml
📒 Files selected for processing (2)
  • app/build.gradle (3 hunks)
  • build.gradle (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • app/build.gradle
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build (windows-latest, 17)
  • GitHub Check: build (windows-latest, 21)
  • GitHub Check: build (ubuntu-latest, 17)
  • GitHub Check: build (macos-latest, 17)
  • GitHub Check: build (ubuntu-latest, 21)
  • GitHub Check: build (macos-latest, 21)

Comment thread build.gradle
dependencies {
classpath 'com.android.tools.build:gradle:8.5.2'
classpath 'com.mxalbert.gradle:jacoco-android:0.2.1'
classpath libs.kotlin.gradle.plugin
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Kotlin Gradle Plugin Dependency Addition

The addition of the Kotlin Gradle plugin via classpath libs.kotlin.gradle.plugin is a crucial change towards enabling Kotlin support. Please ensure that the libs.kotlin.gradle.plugin reference is correctly defined (e.g., in a version catalog like libs.versions.toml) and corresponds to the desired Kotlin version for the project. If not, consider explicitly specifying the version to avoid resolution issues.

@codecov
Copy link
Copy Markdown

codecov Bot commented Mar 18, 2025

Codecov Report

Attention: Patch coverage is 0% with 77 lines in your changes missing coverage. Please review.

Project coverage is 10.84%. Comparing base (7eae112) to head (de8e675).
Report is 6 commits behind head on main.

Files with missing lines Patch % Lines
...limu/kukariri/assessment/WordAssessmentActivity.kt 0.00% 77 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main      #54      +/-   ##
============================================
- Coverage     11.55%   10.84%   -0.71%     
  Complexity        9        9              
============================================
  Files            10       10              
  Lines           199      212      +13     
  Branches         37       37              
============================================
  Hits             23       23              
- Misses          175      188      +13     
  Partials          1        1              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@tuancoltech
Copy link
Copy Markdown
Member Author

@jo-elimu It seems codecov doesn't cover Kotlin code.
Do you have any idea why?

@jo-elimu
Copy link
Copy Markdown
Member

It seems codecov doesn't cover Kotlin code.
Do you have any idea why?

@tuancoltech As far as I know, none of the Kotlin files are covered by unit tests?: https://app.codecov.io/gh/elimu-ai/kukariri/tree/main/app%2Fsrc%2Fmain%2Fjava%2Fai%2Felimu%2Fkukariri%2Flogic

I guess codecov is showing a warning since the overall coverage percentage was reduced. Every time we we add additional lines of code without test coverage, the percentage will be reduced. For this pull request, I see +186 −169 changes, so since more lines of code were added than removed, the code coverage percentage dropped. If we remove lines or code, the code coverage percentage will increase.

@tuancoltech
Copy link
Copy Markdown
Member Author

It seems codecov doesn't cover Kotlin code.
Do you have any idea why?

@tuancoltech As far as I know, none of the Kotlin files are covered by unit tests?: https://app.codecov.io/gh/elimu-ai/kukariri/tree/main/app%2Fsrc%2Fmain%2Fjava%2Fai%2Felimu%2Fkukariri%2Flogic

I guess codecov is showing a warning since the overall coverage percentage was reduced. Every time we we add additional lines of code without test coverage, the percentage will be reduced. For this pull request, I see +186 −169 changes, so since more lines of code were added than removed, the code coverage percentage dropped. If we remove lines or code, the code coverage percentage will increase.

@jo-elimu The codecov coverage action was failed. Do you think it's because the percentage is reduced?

@jo-elimu
Copy link
Copy Markdown
Member

jo-elimu commented Mar 18, 2025

@tuancoltech I'm not 100% sure, but yes, I think codecov status checks fail if the overall coverage percentage goes down. And show as passed (green) whenever the coverage percentage remains unchanged or increases.

@tuancoltech
Copy link
Copy Markdown
Member Author

@tuancoltech I'm not 100% sure, but yes, I think codecov build fail if the overall coverage percentage goes down. And show as passed (green) whenever the coverage percentage remains unchanged or increases.

@jo-elimu Thanks. Let me just merge this PR for now then.

@tuancoltech tuancoltech merged commit e663e7a into main Mar 18, 2025
6 of 8 checks passed
@tuancoltech tuancoltech deleted the convert_word_assessmen_to_kotlin branch March 18, 2025 09:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done ☑️

Development

Successfully merging this pull request may close these issues.

2 participants