在Scala中增加Short类型变量的最简洁方法是什么?
发布时间:2020-12-16 08:56:10 所属栏目:安全 来源:网络整理
导读:我最近一直在研究在 Scala中实现二进制网络协议.数据包中的许多字段自然地映射到Scala Shorts.我想简要地增加一个Short变量(不是一个值).理想情况下,我想要像s = 1(适用于Ints). scala var s = 0:Shorts: Short = 0scala s += 1console:9: error: type misma
我最近一直在研究在
Scala中实现二进制网络协议.数据包中的许多字段自然地映射到Scala Shorts.我想简要地增加一个Short变量(不是一个值).理想情况下,我想要像s = 1(适用于Ints).
scala> var s = 0:Short s: Short = 0 scala> s += 1 <console>:9: error: type mismatch; found : Int required: Short s += 1 ^ scala> s = s + 1 <console>:8: error: type mismatch; found : Int required: Short s = s + 1 ^ scala> s = (s + 1).toShort s: Short = 1 scala> s = (s + 1.toShort) <console>:8: error: type mismatch; found : Int required: Short s = (s + 1.toShort) ^ scala> s = (s + 1.toShort).toShort s: Short = 2 =运算符未在Short上定义,因此在添加之前似乎有一个隐式转换为Int.此外,Short的运算符返回Int. scala> var i = 0 i: Int = 0 scala> i += 1 scala> i res2: Int = 1 现在我将使用s =(s 1).toShort 有任何想法吗? 解决方法
您可以定义一个将Int转换为Short的隐式方法:
scala> var s: Short = 0 s: Short = 0 scala> implicit def toShort(x: Int): Short = x.toShort toShort: (x: Int)Short scala> s = s + 1 s: Short = 1 编译器将使用它来使类型匹配.请注意,虽然implicits也有缺陷,但某些地方你可能会发生转换,甚至不知道原因,只是因为该方法是在范围内导入的,代码可读性也会受到影响. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |