具有通用返回类型的可选函数参数 [英] Optional function parameter with generic return type

查看:44
本文介绍了具有通用返回类型的可选函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您将如何实现通过正则表达式解析某些输入并将建立的字符串转换为其他类型的类?我的方法是:

How would you implement class that parses some input via regex and transforms founded string to some other type? My approach is:

class ARegex[T](regex:Regex, reform:Option[String => T]){
  def findFirst(input:String):Option[T] = {
    (regex.findFirstIn(input), reform) match{
      case (None, _) => None
      case (Some(s), None) => Some(s) // this won't compile because of type mismatch
      case (Some(s), Some(fun)) => Some(fun(s))
    }
  }
}

class BRegex[T](regex:Regex, reform:Option[String => T]) {
  def findFirst(input:String) = {  //returns Option[Any] - erasure
    (regex.findFirstIn(input), reform) match{
      case (None, _) => None
      case (Some(s), None) => Some(s)
      case (Some(s), Some(fun)) => Some(fun(s))
    }
  }
}

推荐答案

我们可以通过去掉reform类型的Option部分来解决这个问题,使用一种不同的机制来表明我们不想以任何方式改变匹配.这个机制就是在不希望类型改变的时候使用identity作为默认参数或者传递identity.

We can solve this problem by eliminating the Option part of the reform's type, and using a different mechanism to indicate that we don't want to change the match in any way. This mechanism is to use identity as a default parameter or pass identity when you don't want the type to change.

class ARegex[T](regex:Regex, reform:String => T = identity[String](_)){
  def findFirst(input:String):Option[T] = {
    regex.findFirstIn(input) match{
      case None => None
      case Some(s) => Some(reform(s))
    }
  }
}

new ARegex("something".r).findFirst("something else") //returns Option[String]
new ARegex("3".r, {x=>x.toInt}).findFirst("number 3") //returns Option[Int]

这篇关于具有通用返回类型的可选函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆