Kotlin for Android Developers
Download 1.04 Mb. Pdf ko'rish
|
Kotlin for Android Developers Learn Kotlin the Easy Way While Developing an Android App ( PDFDrive )
- Bu sahifa navigatsiya:
- 10.2 Shaping the domain layer
Companion objects
Kotlin allows to declare objects to define static behaviours. In Kotlin, we can’t create static properties or functions, but we need to rely on objects. However, these objects make some well known patterns such as Singleton very easy to implement. If we need some static properties, constants or functions in a class, we can use a companion object. This object will be shared among all instances of the class, the same as a static field or method would do in Java. Check the resulting code: 1 class ForecastRequest(val zipCode: String) { 2 3 companion object { 4 private val APP_ID = "15646a06818f61f7b8d7823ca833e1ce" 5 private val URL = "http://api.openweathermap.org/data/2.5/" + 6 "forecast/daily?mode=json&units=metric&cnt=7" 7 private val COMPLETE_URL = "$URL&APPID=$APP_ID&q=" 8 } 9 10 fun execute(): ForecastResult { 11 val forecastJsonStr = URL(COMPLETE_URL + zipCode).readText() 12 return Gson().fromJson(forecastJsonStr, ForecastResult::class.java) 13 } 14 } Remember you need to add Gson library to build.gradle dependencies: 1 compile "com.google.code.gson:gson:2.4" 10.2 Shaping the domain layer Now we’ll create a new package representing the domain layer. It will contain some Command s in charge of performing the use cases of the app. First, a definition of a Command is required: 10 Parsing data 35 1 public interface Command 2 fun execute(): T 3 } These commands will execute an operation and return an object of the class specified in its generic type. It’s interesting to know that every function in Kotlin returns a value. By default, if nothing is specified, it will return an object of the Unit class. So if we want our Command to return nothing, we can specify Unit as its type. Interfaces in Kotlin are more powerful than Java (prior to Java 8), because they can contain code. But for now, we don’t need more than what we could do in a Java interface. Future chapters will elaborate this topic further. The first command needs to request the forecast to the API and convert it to domain classes. This is the definition of the domain classes: 1 data class ForecastList(val city: String, val country: String, 2 val dailyForecast:List 3 4 data class Forecast(val date: String, val description: String, val high: Int, 5 val low: Int) These classes will probably need to be reviewed in the future, when more features are added. But the data they keep is enough for now. Classes must be mapped from the data to the domain model, so the next task will be to create a DataMapper : 1 public class ForecastDataMapper { 2 3 fun convertFromDataModel(forecast: ForecastResult): ForecastList { 4 return ForecastList(forecast.city.name, forecast.city.country, 5 convertForecastListToDomain(forecast.list)) 6 } 7 8 private fun convertForecastListToDomain(list: List 9 List 10 return list.map { convertForecastItemToDomain(it) } 11 } 12 13 private fun convertForecastItemToDomain(forecast: Forecast): ModelForecast { 14 return ModelForecast(convertDate(forecast.dt), 15 forecast.weather[0].description, forecast.temp.max.toInt(), 10 Parsing data 36 16 forecast.temp.min.toInt()) 17 } 18 19 private fun convertDate(date: Long): String { 20 val df = DateFormat.getDateInstance(DateFormat.MEDIUM, 21 Locale.getDefault()) 22 return df.format(date * 1000) 23 } 24 } As we are using two classes with the same name, we can give a specific name to one of them so that we don’t need to write the complete package: 1 import com.antonioleiva.weatherapp.domain.model.Forecast as ModelForecast Another interesting thing about this code is the way to convert the forecast list from the data to the domain model: 1 return list.map { convertForecastItemToDomain(it) } In a single line, we can loop over the collection and return a new list with the converted items. Kotlin provides a good set of functional operations over lists, which apply an operation for all the items in a list and transform them in any way. This is one of the most powerful features in Kotlin for developers used to Java 7. We’ll take a look at all the different transformations very soon. It’s important to know they exist, because it will be much easier to find places where these functions can save a lot of time and boilerplate. And now, everything is ready to write the command: 1 class RequestForecastCommand(val zipCode: String) : 2 Command 3 override fun execute(): ForecastList { 4 val forecastRequest = ForecastRequest(zipCode) 5 return ForecastDataMapper().convertFromDataModel( 6 forecastRequest.execute()) 7 } 8 } Download 1.04 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling