読者です 読者をやめる 読者になる 読者になる

by shigemk2

当面は技術的なことしか書かない

implicitの使い方など

Scala

暗黙の引数として扱えるアレ。

scala> def f(n:Int)(implicit m:Int) = n + m
f: (n: Int)(implicit m: Int)Int

scala> implicit val iv: Int = 123
iv: Int = 123

scala> f(5)
res0: Int = 128

scala> f(1)(10)
res1: Int = 11

scala> implicit val v2: Int = 123
v2: Int = 123

scala> f(1)
<console>:14: error: ambiguous implicit values:
 both value iv of type => Int
 and value v2 of type => Int
 match expected type Int
       f(1)
        ^

scala> f()
<console>:14: error: not enough arguments for method f: (n: Int)(implicit m: Int)Int.
Unspecified value parameter n.
       f()
        ^

scala> implicitly[Int]
<console>:13: error: ambiguous implicit values:
 both value iv of type => Int
 and value v2 of type => Int
 match expected type Int
       implicitly[Int]
                 ^

Scalaメソッド定義メモ(Hishidama's Scala def Memo)