することはできる方法が内蔵型スカラ?
-
08-07-2019 - |
質問
付け加えたいと思い方法が内蔵タイプなどダブル)で、できたらいいのに使用し infix
オペレーターそんなことが可能なのでしょうか?
解決
あります。あいなかったということではないか う などを追加する方法 double
.例えば:
class MyRichDouble(d: Double) {
def <>(other: Double) = d != other
}
implicit def doubleToSyntax(d: Double) = new MyRichDouble(d)
このコードを追加した-利用不可 <>
オペレーターを他の型のオブジェクト Double
.という doubleToSyntax
方法は対象範囲をできるように呼び出されない資格下記のす:
3.1415 <> 2.68 // => true
の"no"の答えをこんんの追加もの Double
クラスです。しかし、皆さんはまったく新しに変換 Double
新しいタイプを定義する方法です。ことができ、より強力な技術の開授業を提供する多くの言語である。いうこともあり完全型安全です。:-)
一部の制限に注意する必要があります。
- この技術はできません 削除 または 再定義 既存の方法で新しいもの
- 暗黙の変換方法(この場合、
doubleToSyntax
)絶対に必要な範囲のための拡張方法で利用可能
Idiomatically、暗黙の変換はされたシングルトンオブジェや輸入例 import Predef._
以内特性を継承した例 class MyStuff extends PredefTrait
).
若干の外"infix事業者"にScalaん。ありませんの魔法の <>
法することができますinfix、パーサは単に受け入れすることができてうれしいです。も利用できます"通常通りの方法"としてinfix事業者に適用されています。例えば、 Stream
クラスを定義します take
方法はシングル Int
パラメータを返します新しい Stream
.これを用いて次のようになっています:
val str: Stream[Int] = ...
val subStream = str take 5
の str take 5
表現は、文字通り一 str.take(5)
.
他のヒント
この機能は、エラー推定を実行するクラスを実装するのに役立ちました:
object errorEstimation {
class Estimate(val x: Double, val e: Double) {
def + (that: Estimate) =
new Estimate(this.x + that.x, this.e + that.e)
def - (that: Estimate) =
new Estimate(this.x - that.x, this.e + that.e)
def * (that: Estimate) =
new Estimate(this.x * that.x,
this.x.abs*that.e+that.x.abs*this.e+this.e*that.e)
def / (that: Estimate) =
new Estimate(this.x/that.x,
(this.x.abs*that.e+that.x.abs*this.e)/(that.x.abs*(that.x.abs-that.e)))
def +- (e2: Double) =
new Estimate(x,e+e2)
override def toString =
x + " +- " + e
}
implicit def double2estimate(x: Double): Estimate = new Estimate(x,0)
implicit def int2estimate(x: Int): Estimate = new Estimate(x,0)
def main(args: Array[String]) = {
println(((x: Estimate) => x+2*x+3*x*x)(1 +- 0.1))
// 6.0 +- 0.93
println(((x: Estimate) => (((y: Estimate) => y*y + 2)(x+x)))(1 +- 0.1))
// 6.0 +- 0.84
def poly(x: Estimate) = x+2*x+3/(x*x)
println(poly(3.0 +- 0.1))
// 9.33333 +- 0.3242352
println(poly(30271.3 +- 0.0001))
// 90813.9 +- 0.0003
println(((x: Estimate) => poly(x*x))(3 +- 1.0))
// 27.037 +- 20.931
}
}