调用存储在地图中的函数

时间:2017-08-02 09:16:03

标签: scala

我想创建一个像这样的地图:

val mapCastMethods = Map("Integer" -> toInt)

然后我想调用与地图一起存储的方法。 类似的东西:

"345".mapCastMethods("Integer")

我该怎么做?

2 个答案:

答案 0 :(得分:3)

我认为这样的事情应该有效:

do{
    guard let entityDic = responseDictionary["Entity"] as? [String: Any] else {return}
    guard let servicesDic = entityDic?["Services"] as? [[String:Any]] else {return}

    for service in services {
        guard let MainServiceCategoryID = service["MainServiceCategories_ID"] as? Int else {return}
        MainServiceCategoriesID.append(MainServiceCategoryID)

        guard let children = service["Children"] as? [[String:Any]] else {return}
        childrenServices.append(children)

        if MainServiceCategoryID == 3 {
            for child in children {
                if let availableService = child["EnglishName"] as? String {
                    servicesNamesArr.append(availableService)
                }
            }
        }            
    }
    print("childrenServices \(childrenServices)")
} catch let error{
    print(error)
}

你应该定义toInt func的函数文字:)

答案 1 :(得分:1)

type Cast[A, X] = A => X
type CastMethods[K, A, X] = Map[K, Cast[A, X]]

implicit def cast[K, A, X](implicit methods: CastMethods[K, A, X]): 
    K => A => X
  = k => a => methods(k)(a)

然后用法:

sealed trait CastMethod
case object Integer extends CastMethod
implicit val methods: CastMethods[CastMethod, String, Int] 
  = Map(Integer -> (_ : String).toInt)

cast.apply(Integer)("345")