相关疑难解决方法(0)

Scala相当于C#的扩展方法?

在C#中你可以写:

using System.Numerics;
namespace ExtensionTest {
public static class MyExtensions {
    public static BigInteger Square(this BigInteger n) {
        return n * n;
    }
    static void Main(string[] args) {
        BigInteger two = new BigInteger(2);
        System.Console.WriteLine("The square of 2 is " + two.Square());
    }
}}
Run Code Online (Sandbox Code Playgroud)

这个简单的扩展方法在Scala中会是什么样子?

extension-methods scala

57
推荐指数
3
解决办法
1万
查看次数

使用asInstanceOf将Any转换为Double?

是否有支持的方法来实现任何数字类型到double的转换.例如

   val i = 12345
   val f = 1234.5F
   val d = 1234.5D
   val arr = Array[Any](i,f,d)
   val anotherD = arr(0).asInstanceOf[Numeric].toDouble
Run Code Online (Sandbox Code Playgroud)

当然,上面的代码不正确 - 因为Numeric需要Type参数.

scala>        val i = 12345
i: Int = 12345

scala>        val f = 1234.5F
f: Float = 1234.5

scala>        val d = 1234.5D
d: Double = 1234.5

scala>        val arr = Array[Any](i,f,d)
arr: Array[Any] = Array(12345, 1234.5, 1234.5)

scala>        val anotherD = arr(0).asInstanceOf[Numeric].toDouble
<console>:11: error: type Numeric takes type parameters
              val anotherD = arr(0).asInstanceOf[Numeric].toDouble
Run Code Online (Sandbox Code Playgroud)

现在我意识到上面的内容可以通过match/case实现,顺序如下:

  (a, …
Run Code Online (Sandbox Code Playgroud)

scala

2
推荐指数
1
解决办法
1666
查看次数

标签 统计

scala ×2

extension-methods ×1