Why don't I get correct result when I use original parseList function in Kotlin?

HelloCW

I'm learning the sample code about Anko at Kotlin for Android Developers (the book) https://github.com/antoniolg/Kotlin-for-Android-Developers

The Method 1 is from sample code and override parseList ,but it's hard to understand.

So I try to use the Method 2 instead of the Method 1, the Method 2 use original parseList function, but I get blank record when I use the Method 2, what error do I made in the Method 2

class DayForecast(var map: MutableMap<String, Any?>) {
  var _id: Long by map
  var date: Long by map
  var description: String by map
  var high: Int by map
  var low: Int by map
  var iconUrl: String by map
  var cityId: Long by map

  constructor(date: Long, description: String, high: Int, low: Int,
              iconUrl: String, cityId: Long) : this(HashMap()) {
    this.date = date
    this.description = description
    this.high = high
    this.low = low
    this.iconUrl = iconUrl
    this.cityId = cityId
  }
}

Method 1

override fun requestForecastByZipCode(zipCode: Long, date: Long) =
  forecastDbHelper.use {
    val dailyRequest = "${DayForecastTable.CITY_ID} = ? AND ${DayForecastTable.DATE} >= ?"
    val dailyForecast = select(DayForecastTable.NAME)
          .whereSimple(dailyRequest, zipCode.toString(), date.toString())
          .parseList { DayForecast(HashMap(it)) }
    /* common code block */
  }

fun <T : Any> SelectQueryBuilder.parseList(parser: (Map<String, Any?>) -> T):
        List<T> = parseList(object : MapRowParser<T> {
  override fun parseRow(columns: Map<String, Any?>): T = parser(columns)
})

Method 2

override fun requestForecastByZipCode(zipCode: Long, date: Long) = 
  forecastDbHelper.use {
    val dailyRequest = "${DayForecastTable.CITY_ID} = ? AND ${DayForecastTable.DATE} >= ?"
    val dailyForecast = select(DayForecastTable.NAME)
          .whereSimple(dailyRequest, zipCode.toString(), date.toString())
          .exec { parseList(classParser<DayForecast>()) }
    /* common code block */
  }
thecoshman

I really do think you should stick to using the 'method 1' approach, it's a lot easier once you realise what Kotlin is letting you do. As I don't know how much you know about Kotlin, I'll try to cover this completely.

The existing class SelectQueryBuilder has (I presume) a function called parseList, that existing function takes a MapRowParser<T>. The MapRowParser<T> has a function parseRow that takes a Map<String, Any?> and returns a T.

In the old Java way of working, you would derive from MapRowParser<T> and would override parseRow so that it does the conversion you want; converting the Map<String, Any?> into a DayForecast (the generic T would now have a type). An instance of this derived class is passed into the existing parseList function. Your derived class would look something like

class MapToDayForecastRowParser extends MapRowParser<DayForecast> {
  @Override public DayForecast parseRow(Map<String, Object> map) {
    // Note that Java's "Object" is more or less Kotlin's "Any?"
    return new DayForecast(map); // Might need to convert the map type btw
  }
}

The extension method is making it really easy to wrap/hide/abstract that creation of the derived class. The extension method take a lambda, that is, you have to parse into the new parseList method a block of code that takes a Map<String, Any?> and returns T (this is what DayForecast(HashMap(it)) is doing, the it is an automatically named variable that is the Map. The extension method then calls the existing parseList method, parsing in an anonymous class that it creates itself. That means that ever use of this extension method creates a new anonymous class, but the Kotlin compiler handles this very well.

One part that did confuse me at first is the way Kotlin handles the anonymous class.

// Java
new MapRowParser<T>() {
  @Override public T parseRow(Map<String, Object>) {
     /* Map to T logic */
  }
}
// Kotlin
object : MapRowParser<T> {
 override fun parseRow(columns: Map<String, Any?>): T = parser(columns)
}

Kotlin also makes it very easy to handle the 'lambda'. It is parsed into the extension method as parser and then set as the implementation of our anonymous class parseRow function. You can also reuse them if you so wished, your so if you need to do the same sort of parsing in lots of places, you can use a named function instead.

The great advantage to this new Kotlin way is that it's very easy focus on what you want to do. With that extension method in place, it's very quick to re-use it so that in another query you can do parseList{ it.getOrDefault("name", "unkown_user") }. You can now easily work on just thinking "If each row is a map, how do I convert that down to a value I want?".

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

I don't quite understand the callback function with a parameter of err or error

来自分类Dev

C++:When creating a new objects inside a function and returning it as result, must I use the new operator to create the object?

来自分类Dev

Why does ACHartEngine LineGraph doesn^t show me any Graph when i use API 10

来自分类Dev

Why I can't bypass function()'s inside hover()?

来自分类Dev

Why can't I use multiple selection with listbox in zk framework?

来自分类Dev

dart, why can't I use generics on a method

来自分类Dev

Why can I not reverse the result of str::split?

来自分类Dev

How can i use a rangeByScore get result withing SPRING-DATA-REDIS

来自分类Dev

How can I get the original resource in ngResource with a responseError interceptor?

来自分类Dev

When Overriding a method, don't we override whole method? I tried to override java.awt.Container.paint

来自分类Dev

Why EXC_BAD_ACCESS (code=EXC_I386_GPFLT) when callback pointer to function?

来自分类Dev

Why can't I use alias from a base class in a derived class with templates?

来自分类Dev

Why isn't $destroy triggered when I call element.remove?

来自分类Dev

Why can't I get the first and last two characters in two strings for a input box?

来自分类Dev

How do I get my aliases to have correct completion?

来自分类Dev

Why do I need depthBuffer to use RenderTexture?

来自分类Dev

How do I efficiently crop an *indexed* Bitmap and get an *indexed* result?

来自分类Dev

Why can't I split this python list?

来自分类Dev

Why can't I create a new Color?

来自分类Dev

Dividing with big(ish) numbers in C (Get a zero, when I know it isn't zero)

来自分类Dev

When can I pass a function handle?

来自分类Dev

ObjectDisposedException when I try to use an Image source

来自分类Dev

Should I use a pointer when dealing with lists?

来自分类Dev

I can't use Windows PowerShell commands

来自分类Dev

When I run AudioBufferSourceNode.start() when I have multiple tracks, I sometimes get a delay

来自分类Dev

Why should I use Using block to connect to the EntityFramework Model?

来自分类Dev

Why is my rails insert slow even if I use thread?

来自分类Dev

Get function result instead of "<function1>"

来自分类Dev

I don't see .bashrc file in my /home and /etc/skel direcories

Related 相关文章

  1. 1

    I don't quite understand the callback function with a parameter of err or error

  2. 2

    C++:When creating a new objects inside a function and returning it as result, must I use the new operator to create the object?

  3. 3

    Why does ACHartEngine LineGraph doesn^t show me any Graph when i use API 10

  4. 4

    Why I can't bypass function()'s inside hover()?

  5. 5

    Why can't I use multiple selection with listbox in zk framework?

  6. 6

    dart, why can't I use generics on a method

  7. 7

    Why can I not reverse the result of str::split?

  8. 8

    How can i use a rangeByScore get result withing SPRING-DATA-REDIS

  9. 9

    How can I get the original resource in ngResource with a responseError interceptor?

  10. 10

    When Overriding a method, don't we override whole method? I tried to override java.awt.Container.paint

  11. 11

    Why EXC_BAD_ACCESS (code=EXC_I386_GPFLT) when callback pointer to function?

  12. 12

    Why can't I use alias from a base class in a derived class with templates?

  13. 13

    Why isn't $destroy triggered when I call element.remove?

  14. 14

    Why can't I get the first and last two characters in two strings for a input box?

  15. 15

    How do I get my aliases to have correct completion?

  16. 16

    Why do I need depthBuffer to use RenderTexture?

  17. 17

    How do I efficiently crop an *indexed* Bitmap and get an *indexed* result?

  18. 18

    Why can't I split this python list?

  19. 19

    Why can't I create a new Color?

  20. 20

    Dividing with big(ish) numbers in C (Get a zero, when I know it isn't zero)

  21. 21

    When can I pass a function handle?

  22. 22

    ObjectDisposedException when I try to use an Image source

  23. 23

    Should I use a pointer when dealing with lists?

  24. 24

    I can't use Windows PowerShell commands

  25. 25

    When I run AudioBufferSourceNode.start() when I have multiple tracks, I sometimes get a delay

  26. 26

    Why should I use Using block to connect to the EntityFramework Model?

  27. 27

    Why is my rails insert slow even if I use thread?

  28. 28

    Get function result instead of "<function1>"

  29. 29

    I don't see .bashrc file in my /home and /etc/skel direcories

热门标签

归档