Generic methods returning dynamic object types

前端 未结 3 1168
情书的邮戳
情书的邮戳 2021-01-30 22:54

Possibly a question which has been asked before, but as usual the second you mention the word generic you get a thousand answers explaining type erasure. I went through that ph

3条回答
  •  误落风尘
    2021-01-30 23:09

    I think you are a static-typed guy, but lemme try: have you thought about using a dynamic language like groovy for that part?

    From your description it seems to me like types are more getting in the way than helping anything.

    In groovy you can let the Cell.valVal be dynamic typed and get an easy transformation around:

    class Cell {
      String val
      def valVal
    }
    
    def cell = new Cell(val:"10.0")
    cell.valVal = cell.val as BigDecimal
    BigDecimal valVal = cell.valVal
    assert valVal.class == BigDecimal
    assert valVal == 10.0
    
    cell.val = "20"
    cell.valVal = cell.val as Integer
    Integer valVal2 = cell.valVal
    assert valVal2.class == Integer
    assert valVal2 == 20
    

    Where as it's everything needed for the most common transformations. You can add yours too.

    If needing to transform other blocks of code, note that java's syntax is valid groovy syntax, except for the do { ... } while() block

提交回复
热议问题