使用格式字符串作为参数改进get year方法中的代码

时间:2019-07-04 21:54:46

标签: kotlin

我正在将一个Android项目迁移到Kotlin并试图提高自己的技能,并且我相信,即使这种方法可行,代码风格也会更好。

由于我对Kotling的编码经验不足,因此我不得不认识到,大多数代码都是由Android Studio直接转换的。这是代码:

 * Formats the movie release date from the TMDB API and returns its year as an int value.
 * If the date is not available, returns the current year.
 *
 * @return int with the release year of the movie.
 */
fun getYear(releaseDate: String): Int {
    val sdf = SimpleDateFormat(
        Constants.TMDB_DATE_FORMAT,
        Locale.getDefault()
    )
    val calendar = GregorianCalendar()
    try {
        calendar.time = sdf.parse(releaseDate)
    } catch (e: ParseException) {
        e.printStackTrace()
    } catch (e: NullPointerException) {
        e.printStackTrace()
    }

    return calendar.get(Calendar.YEAR)
}

我很确定可以改善NullPointerException的try catch。

任何帮助将不胜感激,

毛里西奥·居尔

0 个答案:

没有答案
相关问题