加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读