在Scala中将字符串转换为运算符 [英] Convert string into operator in Scala

查看:253
本文介绍了在Scala中将字符串转换为运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将Scala中的字符串转换为相应的运算符? 给定两个整数和字符串"+",我想要将这两个整数相加的结果.

How can I convert a string in Scala into a corresponding operator? Given two integers and the string "+" I want the result of adding these two integers.

推荐答案

最后一个问题很简单:

def applyOperator(x: Int, y: Int, operator: String) = operator match {
  case "+" => x + y
  case "-" => x - y
  ...
}

可以尝试使用Twitter的Eval库或反射,但是鉴于更简单的解决方案,我不建议您使用它.

You could try using Twitter's Eval library or reflection, but I wouldn't recommend it given the simpler solution.

对于第一个问题:运算符本身不是值,因此您不能将字符串转换为运算符".但是您可以接近:将字符串转换为一个函数,该函数将添加(或减去等)其参数:

For the first question: operators themselves aren't values, so you can't "convert a string into an operator". But you can come close: convert a string into a function which will add (or subtract, etc.) its arguments:

def stringToOperator(operator: String): (Int, Int) => Int = operator match {
  case "+" => _ + _
  case "-" => _ - _
  ...
}

您甚至可以泛化它,使其不仅适用于整数:

You can even generalize it a bit to work not just on integers:

def stringToOperator[A: Numeric](operator: String): (A, A) => A = operator match { ... }

(这显然也适用于第一个答案.)

(This also applies to the first answer in the obvious way.)

这篇关于在Scala中将字符串转换为运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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