Scala中的类型安全格式化输出
发布时间:2020-12-16 09:06:55 所属栏目:安全 来源:网络整理
导读:我在想是否可以在 Scala中实现类型安全的printf.假设我们只需要支持字符串文字,%s和%d 我想要编译printf(“这是数字%d”,0)但是printf(“这是数字%d”,“abc”)不是. 我想printf在编译时检查参数的数量.因此printf(“这是一个文字”)将被编译,但printf(
我在想是否可以在
Scala中实现类型安全的printf.假设我们只需要支持字符串文字,%s和%d
我想要编译printf(“这是数字%d”,0)但是printf(“这是数字%d”,“abc”)不是. 我想printf在编译时检查参数的数量.因此printf(“这是一个文字”)将被编译,但printf(“这是数字%d和字符串%s”,0)不会. 我已经看到它可以用宏来完成.是否绝对需要宏来实现类型安全的printf? 解决方法
这是尝试在没有宏的情况下实现这样的事情.可能有一种不那么丑陋的方式……应该添加一些额外的方法以使其更方便.
import scala.language.implicitConversions package test { sealed trait End sealed trait Prove[T] object Prove{ implicit object EndProve extends Prove[F[End,End]] } class F[A,B](ss: List[String]){ def _d(s: String) = new F[Int,F[A,B]](s :: ss) def _s(s: String) = new F[String,B]](s :: ss) } } package object test { implicit def string2F(s: String) = new F[End,End](List(s)) def printf[A,B](a: A)(f: F[A,B])(implicit ev: Prove[B]) = ??? def printf[A,B,C](b: B,a: A)(f: F[A,F[B,C]])(implicit ev: Prove[C]) = ??? def printf[A,C,D](c: C,b: B,F[C,D]]])(implicit ev: Prove[D]) = ??? // and so on... } 正如您所看到它确实有效(如果您实现实际打印): scala> import test._ import test._ scala> printf(4,"string")("a digit: " _d " and a String: " _s ".") // compiles scala.NotImplementedError: an implementation is missing scala> printf(4,6)("a digit: " _d " and a String: " _s ".") // doesn't compile <console>:11: error: type mismatch; scala> printf(4)("a digit: " _d " and a String: " _s ".") // doesn't compile <console>:11: error: type mismatch; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- twitter-bootstrap – Twitter Bootstraps config.json –
- WebService从零到项目开发使用2—技术研究之Axis2
- Shell替换:Shell变量替换,命令替换,转义字符
- angular2-template-loader无法内联组件模板
- yum update,如何使rpm包更新
- .netcore 使用surging框架发布到docker
- 打字稿 – 如何在angular2中使用带有Observable的ag-grid?
- bash编程及多命令
- bash – 使用终端(或Shell)将文件的一部分复制/粘贴到另一个
- 需要裁剪调整大小?300000个文件.运行时间= 4天.如何加速我的