[kotlin] 날씨 api 확장함수로 데이터 변환하기

찌니·2022년 10월 12일
0

Android(Compose)

목록 보기
2/12

확장함수(extension function)은 기존에 정의된 클래스에 함수를 추가하는 기능이다.
toString, toInt, run, apply 등이 확장함수에 포함된다.

예시로 날씨 api를 사용할때의 확장함수를 정의해보았습니다.

날씨 api 데이터에는 강수형태, 습도, 하늘상태, 기온 등이 오며 확장함수를 통해 데이터를 정제해보겠습니다

실제로 오는 데이터 형식

강수형태 : "0"~"7"
하늘 상태 : "1"~"3"
기온 : -
습도 : -

확장함수 정의하기

data class WeatherData(
                        var rainType : String = "입력없음",
                        var humidity : String = "입력없음",
                        var sky : String = "입력없음",
                        var temp : String = "입력없음"
)

fun WeatherData.getWeather(): WeatherData {
        this.sky = when (this.sky) {
            "1" -> "맑음"
            "3" -> "구름 많음"
            "4" -> "흐림"
            else -> "오류 sky : " + sky
        }
        this.rainType = when (rainType) {
            "0" -> "강수 예정 없음"
            "1" -> "비"
            "2" -> "비/눈"
            "3" -> "눈"
            "5" -> "빗방울"
            "6" -> "빗방울 눈날림"
            "7" -> "눈날림"
            else -> "오류 rainType" + rainType
        }
        return this
    }

사용

call.enqueue(object : retrofit2.Callback<Weather> {
                override fun onResponse(call: Call<Weather>, response: Response<Weather>) {
                    if (response.isSuccessful) {
                        try {
                            val _weather = WeatherData()

                            val weatherData: ArrayList<Weather.Item> = response.body()!!.response.body.items.item
                            val total = response.body()!!.response.body.totalCount

                            for (i in 0 until total step 6) {
                                when (weatherData[i].category) {
                                    "PTY" -> _weather.rainType = weatherData[i].fcstValue // 강수형태
                                    "REH" -> _weather.humidity = weatherData[i].fcstValue // 습도
                                    "SKY" -> _weather.sky = weatherData[i].fcstValue // 하늘상태
                                    "T1H" -> _weather.temp = weatherData[i].fcstValue // 기온
                                }
                            }
                            weather.value = _weather.getWeather()
                        } catch (e: NullPointerException) {
                        }
                    }
                }
profile
찌니's develog

0개의 댓글