Skip to content
Kavachकवच

Data Types: Converting types

● Beginner4 min

Convert a value with the name of the type you want: Float(n), Int(text), String(x).

Kavach doesn't mix number types on its own. This is refused, with the fix in the message:

fn main() {
    const n: Int = 7
    const f: Float = 2.5
    print(n + f)
}

The compiler refused the program:

kavach run no-mixing.kav

error: there are no implicit number conversions: expected `Int`, found `Float`; convert with `Int(…)`
no-mixing.kav: Kavach code, then what running it prints

Say what you want with the type's name:

fn main() {
    const n: Int = 7
    const f = Float(n) / 2.0
    print(f)
    const typed = "42"
    const parsed = Int(typed) catch _ => 0
    print(parsed + 1)
    const answer = "forty-two"
    const bad = Int(answer) catch _ => -1
    print(bad)
    print(Int("2") + Int("2"))
}

The program ran and printed:

kavach run convert.kav

3.543-14
convert.kav: Kavach code, then what running it prints
  • Float(n) always works. Int(2.7) cuts the fraction off: 2.
  • Text may not be a number, so Int(text) can fail, and you must say what happens then: catch _ => 0 uses 0. Errors have their own part of the course.
  • When the text is written in the code, as in Int("2"), the compiler reads it itself.

Numbers written straight in the code may mix, because the compiler knows their exact values. Typed values say which way to go:

fn main() {
    print(2 + 2.4)
    const n: Int = 2
    const f: Float = 2.4
    print(Float(n) + f)
    print(n + Int(f))
}

The program ran and printed:

kavach run mixing.kav

4.44.44
mixing.kav: Kavach code, then what running it prints

What Kavach does for you

  • Text to number can fail, and says so

    Int("23sd") is an error you must handle, never a silent 0 or a guess.

    spec 2.1