I would say your problem is that you have two types that you want to work on: Int and String, and you want to execute the key method on this input, but you will not indicate that you like to return.
My first idea for Int is to return Int. toString (). charAt (n) looks like a form of cheating, but perhaps the cheating is fine, so let's start cheating:
def cheat (a: Any, n: Int) = a.toString ().charAt (n)
cheat (2345, 2)
cheat ("foobar", 2)
, ? , Int Int String ? Char String, 0 9, , T T.
, , - , ?
class Atti [T] (val fun: (Int => T)) {
def at (n: Int): T = fun (n)
}
-, T , Int T, at , .
iGet, Int n, ,...
def iGet (i: Int) (n: Int) : Int = {
if (n == 0) i % 10
else iGet (i / 10)(n - 1) }
... Int, , :
val iAt = new Atti[Int] (iGet (2345) _)
(0 to 3).map (iAt.at (_))
// res412: scala.collection.immutable.IndexedSeq[Int] = Vector(5, 4, 3, 2)
sAt:
def sGet (s: String) (n: Int) : String = "" + s.charAt (n)
val sAt = new Atti[String] (sGet ("foobar") _)
(0 to 3).map (sAt.at (_))
, , String , Int , .
, , sAt foobar String, 2345 - iAt-.
, , , , , .
Int String, :
trait Key [T] { def at (n: Int): T }
val s : String with Key[String] = "Foobar" { def at (n: Int) : String = "" + s.charAt (n) }
<console>:7: error: type mismatch;
found : Unit
required: Int
val s : String with Key[String] = "Foobar" { def at (n: Int) : String = "" + s.charAt (n) }
^